incanto 0.9.0 → 0.11.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.
@@ -1,4 +1,4 @@
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=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}},n=class{changed=new t;_master=1;_sfx=1;_music=1;_muted=!1;get master(){return this._master}set master(e){this._master=this.assign(this._master,e)}get sfx(){return this._sfx}set sfx(e){this._sfx=this.assign(this._sfx,e)}get music(){return this._music}set music(e){this._music=this.assign(this._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*r(t)}assign(e,t){if(!Number.isFinite(t))return e;let n=r(t);return n!==e&&this.changed.emit(),n}};function r(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}function i(e,t,n){let r=o(e,t);return n===`in`?r:1-r}function a(e,t){let n=o(e,t)*Math.PI/2;return{out:s(Math.cos(n)),in:s(Math.sin(n))}}function o(e,t){return!Number.isFinite(e)||t<=0?1:s(e/t)}function s(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var c=null,l=null;function u(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function d(){if(c)return c();let e=u();return e?new e:null}function f(){return l?l():typeof Audio>`u`?null:new Audio}var p={src:``,setGain(){},setLoop(){},play(){},stop(){}},m=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}},h=class{ctx=null;resolved=!1;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=d(),!0),this.ctx}createTrack(e){let t=this.ensure(),n=f();return!t||!n?{...p,src:e}:(t.state===`suspended`&&t.resume(),new m(e,n,t))}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}},g=null,_=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=g?g(this.buses):new h;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=v(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=a(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`?i(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`?i(this.outgoing.t,this.outgoing.duration,`out`):0;this.outgoing.track.setGain(e*t)}}killOutgoing(){this.outgoing?.track.stop(),this.outgoing=null}};function v(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var y=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`IncantoError`,this.code=e,this.details=n}},b=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 y(`BAD_FORMAT`,`Rng.pick needs a non-empty array.`);return e[this.int(0,e.length-1)]}},x={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}},S=Object.keys(x),C=Math.PI*2;function w(e,t={}){let n=t.sampleRate??44100,r=t.pitch??1,i=new b((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(C*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(C*d);break;default:p-=m/n,p<=0&&(f=i.range(-1,1),p+=1),h=f;break}s[t]=T(h*o*e.volume)}return s}function T(e){return e<-1?-1:e>1?1:e}var E=[`inverse`,`linear`,`exponential`];function D(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=O(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)?ee(o):0}function O(e,t,n){return e<t?t:e>n?n:e}function ee(e){return e<0?0:e>1?1:e}var k={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}},te={set:()=>{},stop:()=>{},stopped:!0};function ne(e,t,n){let r=k[t]??k.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 re=te;function ie(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 ae(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 oe=null;function se(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function ce(){if(oe)return oe();let e=se();return e?new e:null}function le(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 ue=class{ctx=null;resolved=!1;pcmCache=new Map;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=ce(),!0),this.ctx}startVoice(e,t=1){let n=this.ensure();return n?(n.state===`suspended`&&n.resume(),ne(n,e,t)):re}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=le(e,a,i),s=this.pcmCache.get(o);s||(s=w(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,ae(t,e.position),r.listener&&ie(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 de(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 fe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>fe(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&&fe(e[n],t[n]))}return!1}function A(e){return typeof e!=`object`||!e?e:JSON.parse(JSON.stringify(e))}function pe(e,t,n){let r=de(t);if(r===`null`)return;let i=de(e);if(i!==r)throw new y(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects ${r} (default ${JSON.stringify(t)}), got ${i} (${JSON.stringify(e)}).`,{prop:n});if(typeof e==`number`&&!Number.isFinite(e))throw new y(`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 y(`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++)pe(e[r],t[r],`${n}[${r}]`)}}var me=new Map;function j(e,t){let n=me.get(e.typeName);if(n&&n!==e&&!t?.replace)throw new y(`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});me.set(e.typeName,e)}function he(e){let t=me.get(e);if(!t){let t=[...me.keys()];throw new y(`UNKNOWN_NODE_TYPE`,`Unknown node type '${e}'. Registered types: [${t.join(`, `)}].`,{nodeType:e,validOptions:t})}return t}function ge(){return[...me.keys()]}function _e(e){return ye(he(e))}function ve(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){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 be(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 xe(e,t,n,r,i={}){for(let[n,r]of Object.entries(t))e[n]=A(r.default);if(n)for(let[a,o]of Object.entries(n)){let n=t[a]?a:i[a]??a,s=t[n];if(!s){let e=Object.keys(t);throw new y(`UNKNOWN_PROP`,`Unknown prop '${a}' on '${r}'. Valid props: [${e.join(`, `)}].`,{prop:a,nodeType:r,validOptions:e})}pe(o,s.default,`${r}.${n}`),e[n]=A(o)}}function Se(e,t){let n=he(e),r=new n;return xe(r,_e(e),t,e,be(n)),r}var M=class{static props;static signals;node;get engine(){let e=this.node?.tree?.engine;if(!e)throw new y(`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)}},Ce=class extends M{},we=new Map;function Te(e){return we.has(e)}function N(e){let t=we.get(e);if(!t){let t=[...we.keys()];throw new y(`UNKNOWN_BEHAVIOR`,`Unknown behavior '${e}'. Registered behaviors: [${t.join(`, `)}]. Did you forget registerBehavior('${e}', ${e})?`,{validOptions:t})}return t}function Ee(e,t){let n=N(e),r=new n;return xe(r,ye(n),t,`script:${e}`),r}var P=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 F(e){let t=e;return!!t&&(t.isContentEditable===!0||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`)}var De=class{actions=new Map;down=new Set;pressedEdge=new Set;releasedEdge=new Set;detach=null;declare(e){for(let[t,n]of Object.entries(e)){let e=n;if(e.type===`button`){let n=e.keys;if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new y(`BAD_FORMAT`,`Input action '${t}': button "keys" must be an array of KeyboardEvent.code strings.`);if(e.touch!==void 0&&e.touch!==`button`)throw new y(`BAD_FORMAT`,`Input action '${t}': button "touch" must be 'button', got ${JSON.stringify(e.touch)}.`);this.actions.set(t,{type:`button`,keys:[...n],...e.touch===`button`?{touch:`button`}:{}})}else if(e.type===`vector2`){let n=e.keys;for(let e of[`up`,`down`,`left`,`right`])if(!Array.isArray(n?.[e]))throw new y(`BAD_FORMAT`,`Input action '${t}': vector2 "keys" needs arrays for up/down/left/right.`);if(e.touch!==void 0&&e.touch!==`joystick`)throw new y(`BAD_FORMAT`,`Input action '${t}': vector2 "touch" must be 'joystick', got ${JSON.stringify(e.touch)}.`);let r=n;this.actions.set(t,{type:`vector2`,keys:{up:[...r.up],down:[...r.down],left:[...r.left],right:[...r.right]},...e.touch===`joystick`?{touch:`joystick`}:{}})}else throw new y(`BAD_FORMAT`,`Input action '${t}': "type" must be 'button' or 'vector2', got ${JSON.stringify(e.type)}.`)}}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 y(`BAD_FORMAT`,`Input action '${e}' is a button — use pressAction/releaseAction, not setActionVector.`);if(!Number.isFinite(t)||!Number.isFinite(n))throw new y(`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.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=>{(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=>{F(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=>{F(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)}getVector(e){let t=this.get(e);if(t.type!==`vector2`)throw new y(`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 y(`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 y(`BAD_FORMAT`,`Input action '${e}' is a vector2 — use getVector, not button queries.`);return t}},Oe=class{added=new t;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)}},ke=.25;function Ae(e){let t=!0,n=requestAnimationFrame(function r(i){t&&(e(i),n=requestAnimationFrame(r))});return()=>{t=!1,cancelAnimationFrame(n)}}var je=class{updated=new t;fixedUpdated=new t;sceneChanged=new t;input=new De;rng;log=new Oe;audio=new n;sfx=new ue;music=new _(this.audio);fixedStep;maxFixedSteps;scheduler;_scene=null;lastMs=null;accumulator=0;disposeScheduler=null;frameStats=new P;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??Ae,this.rng=new b(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),this.sceneChanged.emit(e))}start(){this.disposeScheduler||=this.scheduler(e=>this.tick(e))}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?Me(this._scene.tree.root):0,running:this.disposeScheduler!==null}}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.min((e-this.lastMs)/1e3,ke),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 Me(e){let t=1;for(let n of e.children)t+=Me(n);return t}function Ne(e){if(e===``)throw new y(`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 y(`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 y(`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 y(`BAD_NODE_PATH`,`Invalid node path '${e}'. '%' is only allowed as a whole-path prefix ('%Name').`);if(t===`.`)throw new y(`BAD_NODE_PATH`,`Invalid node path '${e}'. '.' is only valid as the whole path — drop the './' prefix.`)}if(t&&r.includes(`..`))throw new y(`BAD_NODE_PATH`,`Invalid node path '${e}'. Absolute paths must not contain '..'.`);return{kind:t?`absolute`:`relative`,segments:r}}function Pe(e){if(e===``||e.includes(`/`)||e.includes(`%`))throw new y(`TREE_VIOLATION`,`Invalid node name '${e}'. Names must be non-empty and must not contain '/' or '%'.`)}var Fe=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,Pe(this._name)}get name(){return this._name}set name(e){Pe(e);let t=this._name;this._parent?this._name=Le(e,this._parent._children,this):this._name=e,this._tree&&this._name!==t&&(this._tree._unindexName(this,t),this._tree._indexName(this))}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 y(`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 y(`TREE_VIOLATION`,`Cannot add '${e.name}' to '${this.name}': it is this node or an ancestor (cycle).`);return e._name=Le(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 y(`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 y(`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=Ne(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 y(`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(Ie(this.getRoot(),t.name,n),n.length>1)throw new y(`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 y(`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 n=this._signals.get(e);return n||(n=new t,this._signals.set(e,n)),n}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){this.update(e),this.behavior?.update?.(e);let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateUpdate(e)}_propagateFixedUpdate(e){this.fixedUpdate(e),this.behavior?.fixedUpdate?.(e);let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateFixedUpdate(e)}onEnterTree(){}onReady(){}onExitTree(){}update(e){}fixedUpdate(e){}};function Ie(e,t,n){e.name===t&&n.push(e);for(let r of e.children)Ie(r,t,n)}function Le(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 Re=null;function ze(){return Re?Re():typeof Audio>`u`?null:new Audio}var Be=class extends Fe{static typeName=`AudioPlayer`;static signals=[`finished`];static props={src:{default:``},preset:{default:`custom`,options:[`custom`,...S]},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:[...E]}};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`&&!S.includes(t.preset))throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' preset must be 'custom' or one of [${S.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:S});if(t.bus!==`sfx`&&t.bus!==`music`)throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' bus must be 'sfx' or 'music', got '${t.bus}'.`,{prop:`bus`,validOptions:[`sfx`,`music`]});if(!E.includes(t.rolloff))throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' rolloff must be one of [${E.join(`, `)}], got '${t.rolloff}'.`,{prop:`rolloff`,validOptions:[...E]})}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 D(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=ze(),!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=x[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)}},Ve={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;`},He=`600 14px system-ui, -apple-system, 'Segoe UI', sans-serif`;function Ue(){return typeof document<`u`}var We=class extends Fe{static typeName=`HudLayer`;static props={zIndex:{default:100},visible:{default:!0}};zIndex=100;visible=!0;_element=null;slots=new Map;onEnterTree(){if(!Ue())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:${He};`,document.body.appendChild(e),this._element=e}onExitTree(){this._element?.remove(),this._element=null,this.slots.clear()}update(){this._element&&(this._element.style.display=this.visible?``:`none`)}_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;${Ve[e]??Ve.topLeft}`,this._element.appendChild(t),this.slots.set(e,t)),t}},Ge=class extends Fe{static props={anchor:{default:`topLeft`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},visible:{default:!0}};anchor=`topLeft`;visible=!0;_element=null;layer(){for(let e=this.parent;e;e=e.parent)if(e instanceof We)return e;return null}onReady(){if(!Ue())return;let e=this.layer()?._slot(this.anchor);e&&(this._element=this._build(),e.appendChild(this._element))}onExitTree(){this._element?.remove(),this._element=null}update(e){this._element&&(this._element.style.display=this.visible?``:`none`,this._sync())}_sync(){}},Ke=class extends Ge{static typeName=`UiText`;static props={...Ge.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(){this.text!==this.last&&this._element&&(this.last=this.text,this._element.textContent=this.text)}},qe=class extends Ge{static typeName=`UiBar`;static props={...Ge.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;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.textContent=this.label,t.style.cssText=`color:#fff;font-size:12px;text-shadow:0 1px 3px rgba(0,0,0,.7);`,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.ratio;e===this.lastRatio||!this.fill||(this.lastRatio=e,this.fill.style.width=`${e*100}%`,this.fill.style.background=e<=this.lowThreshold?this.lowColor:this.color)}},Je=class extends Ge{static typeName=`UiBanner`;static signals=[`bannerShown`];static props={...Ge.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.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))}},Ye=class extends Ge{static typeName=`UiButton`;static signals=[`pressed`];static props={...Ge.props,text:{default:`OK`},size:{default:16},color:{default:`#ffffff`},background:{default:`rgba(255,255,255,0.14)`},disabled:{default:!1}};text=`OK`;size=16;color=`#ffffff`;background=`rgba(255,255,255,0.14)`;disabled=!1;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(){this._element&&(this.text!==this.lastText&&(this.lastText=this.text,this._element.textContent=this.text),this._element.disabled=this.disabled,this._element.style.opacity=this.disabled?`0.45`:`1`)}},Xe=class extends Ge{static typeName=`UiDialogue`;static signals=[`lineShown`,`choiceMade`,`dialogueFinished`];static props={...Ge.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.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)})}},Ze=class extends Fe{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}}},Qe=.5*(Math.sqrt(3)-1),$e=(3-Math.sqrt(3))/6,et=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,0,1,0,-1]);function tt(e){let t=new b(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)*Qe,i=Math.floor(e+r),a=Math.floor(t+r),o=(i+a)*$e,s=e-(i-o),c=t-(a-o),l=+(s>c),u=s>c?0:1,d=s-l+$e,f=c-u+$e,p=s-1+2*$e,m=c-1+2*$e,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*(et[e]*s+et[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*(et[e]*d+et[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*(et[e]*p+et[e+1]*m)}return 70*_}}var nt={background:-2e3,terrain:-1e3,default:0,characters:1e3,effects:2e3,overlay:3e3};function rt(e,t){return(nt[e]??0)+t}var it={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`}},at=Object.keys(it);function ot(e,t,n){if(t===`custom`)return;let r=it[t];if(r)for(let[t,i]of Object.entries(r)){let r=n[t]?.default,a=e[t];r!==void 0&&fe(a,r)&&(e[t]=Array.isArray(i)?[...i]:i)}}var st=9,ct=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)*st)}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*st,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*st,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*st,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*st,t*st,t*st+st),this.alive=t}};function lt(){j(Fe),j(Ze),j(Be),j(We),j(Ke),j(qe),j(Je),j(Ye),j(Xe)}function ut(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}}var dt=`@const`;function ft(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 pt(e,t){if(e==null)return e;if(ft(e)){let n=e[dt];if(!t||!(n in t)){let e=t?Object.keys(t):[];throw new y(`UNKNOWN_CONSTANT`,`Unknown constant '@const: ${n}'. Declared constants: ${e.length?e.join(`, `):`(none — add a "constants" section)`}.`)}return A(t[n])}if(Array.isArray(e))return e.map(e=>pt(e,t));if(typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=pt(i,t);return n}return e}var mt=class{_root=null;_engine=null;freeQueue=new Set;_nameIndex=new Map;_structureVersion=0;_frameId=0;get frameId(){return this._frameId}_indexName(e){this._structureVersion++;let t=this._nameIndex.get(e.name);t||(t=new Set,this._nameIndex.set(e.name,t)),t.add(e)}_unindexName(e,t=e.name){this._structureVersion++;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 y(`TREE_VIOLATION`,`SceneTree already has a root.`);if(e.parent)throw new y(`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&&ht(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 ht(e,t,n){e.isInGroup(t)&&n.push(e);for(let r of e.children)ht(r,t,n)}var gt=[`expand`,`letterbox`,`integer`];function _t(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 y(`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`||!gt.includes(n))throw new y(`BAD_FORMAT`,`Scene "viewport.fit" must be one of [${gt.join(`, `)}], got ${JSON.stringify(n)}.`);return{design:[t[0],t[1]],fit:n}}function vt(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 yt(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=A(e.tags));let r=_e(t.typeName),i={};for(let[t,n]of Object.entries(r)){let r=e[t];r!==void 0&&(bt(r,`${e.name}.${t}`),fe(r,n.default)||(i[t]=A(r)))}return Object.keys(i).length>0&&(n.props=i),e.script&&(n.script=A(e.script)),e.network&&(n.network=A(e.network)),e.children.length>0&&(n.children=e.children.map(e=>yt(e))),n}function bt(e,t){if(typeof e==`number`&&!Number.isFinite(e))throw new y(`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++)bt(e[n],`${t}[${n}]`);else if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e))bt(r,`${t}.${n}`)}var xt=class{name;dimension;root;tree;environment;assets;constants;input;physics;multiplayer;viewport;connections;source;constructor(e,t,n){this.source=A(e),this.name=e.name,this.dimension=e.dimension,this.root=t,this.tree=n,this.assets=e.assets?A(e.assets):void 0,this.constants=e.constants?A(e.constants):void 0,this.input=e.input?A(e.input):void 0,this.physics=e.physics?A(e.physics):void 0,this.multiplayer=e.multiplayer?A(e.multiplayer):void 0,this.environment=e.environment?A(e.environment):void 0,this.viewport=e.viewport?A(e.viewport):void 0,this.connections=e.connections?A(e.connections):[]}toJSON(){return{format:1,type:`scene`,name:this.name,...this.dimension?{dimension:this.dimension}:{},...this.assets?{assets:A(this.assets)}:{},...this.constants?{constants:A(this.constants)}:{},...this.input?{input:A(this.input)}:{},...this.physics?{physics:A(this.physics)}:{},...this.multiplayer?{multiplayer:A(this.multiplayer)}:{},...this.environment?{environment:A(this.environment)}:{},...this.viewport?{viewport:A(this.viewport)}:{},root:yt(this.root),...this.connections.length>0?{connections:A(this.connections)}:{}}}};function St(e,t){if(typeof e!=`object`||!e)throw new y(`BAD_FORMAT`,`Scene JSON must be an object, got ${e===null?`null`:typeof e}.`);let n=e;wt(n);let r=Et(n.root,t,[],``,n.constants);Pt(r);let i=new mt;return t?.engine&&i._setEngine(t.engine),i.setRoot(r),jt(r,n.connections??[],t?.declareConnectionSignals),new xt(n,r,i)}function Ct(e,t){return Et(e,t,[],``,void 0)}function wt(e){if(e.format!==1)throw new y(`BAD_FORMAT`,`Unsupported scene format ${JSON.stringify(e.format)}; this engine reads format 1.`);if(e.type!==`scene`)throw new y(`BAD_FORMAT`,`Expected "type": "scene", got ${JSON.stringify(e.type)}.`);if(typeof e.name!=`string`||e.name===``)throw new y(`BAD_FORMAT`,`Scene "name" must be a non-empty string.`);if(e.dimension!==void 0&&e.dimension!==`2d`&&e.dimension!==`3d`)throw new y(`BAD_FORMAT`,`Scene "dimension" must be "2d" or "3d", got ${JSON.stringify(e.dimension)}.`);if(typeof e.root!=`object`||e.root===null)throw new y(`BAD_FORMAT`,`Scene "root" must be a node object.`);_t(e.viewport)}function Tt(e,t,n){return e instanceof y&&!e.details.path?new y(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 Et(e,t,n,r,i){let a=`${r}/${e.name}`;try{if(e.instance!==void 0&&e.type!==void 0)throw new y(`BAD_FORMAT`,`Node '${e.name}' declares both "type" and "instance" — they are mutually exclusive.`);if(e.instance!==void 0)return Dt(e,t,n,a,i);if(e.type===void 0)throw new y(`BAD_FORMAT`,`Node '${e.name}' must declare either "type" or "instance".`);let r=Se(e.type,pt(e.props,i));kt(r,e,t),r.constructor.validateJson?.(r);for(let o of e.children??[])r.addChild(Et(o,t,n,a,i));return r}catch(t){throw Tt(t,a,e)}}function Dt(e,t,n,r,i){let a=e.instance;if(!t?.resolveScene)throw new y(`UNRESOLVED_INSTANCE`,`Node '${e.name}' references instance '${a}' but no resolveScene option was provided.`);if(n.includes(a))throw new y(`UNRESOLVED_INSTANCE`,`Instance cycle detected: ${[...n,a].join(` → `)}.`);let o=t.resolveScene(a);if(!o)throw new y(`UNRESOLVED_INSTANCE`,`resolveScene returned nothing for instance '${a}' (node '${e.name}').`);wt(o);let s=pt(e.overrides??{},i),c=Et({...o.root,name:e.name,props:At(o.root.props??{},s)},t,[...n,a],Ot(r),o.constants);kt(c,{...e,type:void 0,props:void 0},t);for(let a of e.children??[])c.addChild(Et(a,t,n,r,i));return jt(c,o.connections??[],t?.declareConnectionSignals),c}function Ot(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function kt(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=A(t.tags)),t.script){e.script=A(t.script);let r=t.script.name;if(typeof r!=`string`||r===``)throw new y(`BAD_FORMAT`,`Node '${t.name}': "script" needs a non-empty "name" (a registered behavior).`);let i=n?.stubMissingBehaviors&&!Te(r)?new class extends Ce{}:Ee(r,t.script.props);i.node=e,e.behavior=i;for(let t of ve(i.constructor))e.declareSignal(t)}t.network&&(e.network=A(t.network))}function At(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]=At(t,r):n[e]=r}return n}function jt(e,t,n=!1){for(let r of t){let t=Mt(e,r.from,r,`from`);(n||t.behavior instanceof Ce)&&t.declareSignal(r.signal);let i=Mt(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 Ce))throw new y(`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&&!Nt(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 y&&e.code===`UNKNOWN_SIGNAL`?new y(`UNKNOWN_SIGNAL`,`Connection from '${r.from}': ${e.message}`,e.details):e}}}function Mt(e,t,n,r){try{return e.getNode(t)}catch(e){throw e instanceof y?new y(`DANGLING_CONNECTION`,`Connection '${n.signal}' has a dangling '${r}' path '${t}': ${e.message}`):e}}function Nt(e,t){if(!(e instanceof Fe)||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 Pt(e){let t=new Map,n=e=>{if(e.uid!==null){let n=t.get(e.uid);if(n)throw new y(`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 Ft(){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 It=`attached`,Lt=1e3,Rt=1001,zt=1002,Bt=1003,Vt=1004,Ht=1005,Ut=1006,Wt=1007,Gt=1008,Kt=1009,qt=1010,Jt=1011,Yt=1012,Xt=1013,Zt=1014,Qt=1015,$t=1016,en=1017,tn=1018,nn=1020,rn=35902,an=35899,on=1021,sn=1022,cn=1023,ln=1026,un=1027,dn=1028,fn=1029,pn=1030,mn=1031,hn=1033,gn=33776,_n=33777,vn=33778,yn=33779,bn=35840,xn=35841,Sn=35842,Cn=35843,wn=36196,Tn=37492,En=37496,Dn=37488,On=37489,kn=37490,An=37491,jn=37808,Mn=37809,Nn=37810,Pn=37811,Fn=37812,In=37813,Ln=37814,Rn=37815,zn=37816,Bn=37817,Vn=37818,Hn=37819,Un=37820,Wn=37821,Gn=36492,Kn=36494,qn=36495,Jn=36283,Yn=36284,Xn=36285,Zn=36286,Qn=2200,$n=2201,er=2202,tr=2300,nr=2301,rr=2302,ir=2303,ar=2400,or=2401,sr=2402,cr=2500,lr=2501,ur=3200,dr=3201,fr=`srgb`,pr=`srgb-linear`,mr=`linear`,hr=`srgb`,gr=7680,_r=35044,vr=35048,yr=2e3;function br(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function xr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Sr(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function Cr(){let e=Sr(`canvas`);return e.style.display=`block`,e}var wr={},Tr=null;function Er(...e){let t=`THREE.`+e.shift();Tr?Tr(`log`,t,...e):console.log(t,...e)}function Dr(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 I(...e){e=Dr(e);let t=`THREE.`+e.shift();if(Tr)Tr(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function L(...e){e=Dr(e);let t=`THREE.`+e.shift();if(Tr)Tr(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Or(...e){let t=e.join(` `);t in wr||(wr[t]=!0,I(...e))}function kr(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 Ar={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},jr=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}}},Mr=`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(`.`),Nr=1234567,Pr=Math.PI/180,Fr=180/Math.PI;function Ir(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Mr[e&255]+Mr[e>>8&255]+Mr[e>>16&255]+Mr[e>>24&255]+`-`+Mr[t&255]+Mr[t>>8&255]+`-`+Mr[t>>16&15|64]+Mr[t>>24&255]+`-`+Mr[n&63|128]+Mr[n>>8&255]+`-`+Mr[n>>16&255]+Mr[n>>24&255]+Mr[r&255]+Mr[r>>8&255]+Mr[r>>16&255]+Mr[r>>24&255]).toLowerCase()}function R(e,t,n){return Math.max(t,Math.min(n,e))}function Lr(e,t){return(e%t+t)%t}function Rr(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function zr(e,t,n){return e===t?0:(n-e)/(t-e)}function Br(e,t,n){return(1-n)*e+n*t}function Vr(e,t,n,r){return Br(e,t,1-Math.exp(-n*r))}function Hr(e,t=1){return t-Math.abs(Lr(e,t*2)-t)}function Ur(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Wr(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Gr(e,t){return e+Math.floor(Math.random()*(t-e+1))}function Kr(e,t){return e+Math.random()*(t-e)}function qr(e){return e*(.5-Math.random())}function Jr(e){e!==void 0&&(Nr=e);let t=Nr+=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 Yr(e){return e*Pr}function Xr(e){return e*Fr}function Zr(e){return(e&e-1)==0&&e!==0}function Qr(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function $r(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ei(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:I(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function ti(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 ni(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 ri={DEG2RAD:Pr,RAD2DEG:Fr,generateUUID:Ir,clamp:R,euclideanModulo:Lr,mapLinear:Rr,inverseLerp:zr,lerp:Br,damp:Vr,pingpong:Hr,smoothstep:Ur,smootherstep:Wr,randInt:Gr,randFloat:Kr,randFloatSpread:qr,seededRandom:Jr,degToRad:Yr,radToDeg:Xr,isPowerOfTwo:Zr,ceilPowerOfTwo:Qr,floorPowerOfTwo:$r,setQuaternionFromProperEuler:ei,normalize:ni,denormalize:ti},z=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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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(R(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}},B=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:I(`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(R(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}},V=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(ai.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ai.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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this.z=R(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this.z=R(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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 ii.copy(this).projectOnVector(e),this.sub(ii)}reflect(e){return this.sub(ii.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(R(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}},ii=new V,ai=new B,H=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(oi.makeScale(e,t)),this}rotate(e){return this.premultiply(oi.makeRotation(-e)),this}translate(e,t){return this.premultiply(oi.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)}},oi=new H,si=new H().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ci=new H().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function li(){let e={enabled:!0,workingColorSpace:pr,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=di(e.r),e.g=di(e.g),e.b=di(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=fi(e.r),e.g=fi(e.g),e.b=fi(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===``?mr: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 Or(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Or(`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({[pr]:{primaries:t,whitePoint:r,transfer:mr,toXYZ:si,fromXYZ:ci,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:fr},outputColorSpaceConfig:{drawingBufferColorSpace:fr}},[fr]:{primaries:t,whitePoint:r,transfer:hr,toXYZ:si,fromXYZ:ci,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:fr}}}),e}var ui=li();function di(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function fi(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var pi,mi=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{pi===void 0&&(pi=Sr(`canvas`)),pi.width=e.width,pi.height=e.height;let t=pi.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=pi}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=Sr(`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]=di(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(di(t[e]/255)*255):t[e]=di(t[e]);return{data:t,width:e.width,height:e.height}}else return I(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},hi=0,gi=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:hi++}),this.uuid=Ir(),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(_i(r[t].image)):e.push(_i(r[t]))}else e=_i(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function _i(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?mi.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(I(`Texture: Unable to serialize Texture.`),{})}var vi=0,yi=new V,bi=class e extends jr{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=Rt,i=Rt,a=Ut,o=Gt,s=cn,c=Kt,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:vi++}),this.uuid=Ir(),this.name=``,this.source=new gi(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 z(0,0),this.repeat=new z(1,1),this.center=new z(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new H,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(yi).x}get height(){return this.source.getSize(yi).y}get depth(){return this.source.getSize(yi).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){I(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){I(`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 Lt:e.x-=Math.floor(e.x);break;case Rt:e.x=e.x<0?0:1;break;case zt: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 Lt:e.y-=Math.floor(e.y);break;case Rt:e.y=e.y<0?0:1;break;case zt: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++}};bi.DEFAULT_IMAGE=null,bi.DEFAULT_MAPPING=300,bi.DEFAULT_ANISOTROPY=1;var xi=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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this.z=R(this.z,e.z,t.z),this.w=R(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this.z=R(this.z,e,t),this.w=R(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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}},Si=class extends jr{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ut,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 xi(0,0,e,t),this.scissorTest=!1,this.viewport=new xi(0,0,e,t),this.textures=[];let r=new bi({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:Ut,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 gi(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`})}},Ci=class extends Si{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},wi=class extends bi{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=Bt,this.minFilter=Bt,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ti=class extends bi{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=Bt,this.minFilter=Bt,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},U=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/Ei.setFromMatrixColumn(e,0).length(),i=1/Ei.setFromMatrixColumn(e,1).length(),a=1/Ei.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(Oi,e,ki)}lookAt(e,t,n){let r=this.elements;return Mi.subVectors(e,t),Mi.lengthSq()===0&&(Mi.z=1),Mi.normalize(),Ai.crossVectors(n,Mi),Ai.lengthSq()===0&&(Math.abs(n.z)===1?Mi.x+=1e-4:Mi.z+=1e-4,Mi.normalize(),Ai.crossVectors(n,Mi)),Ai.normalize(),ji.crossVectors(Mi,Ai),r[0]=Ai.x,r[4]=ji.x,r[8]=Mi.x,r[1]=Ai.y,r[5]=ji.y,r[9]=Mi.y,r[2]=Ai.z,r[6]=ji.z,r[10]=Mi.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],ee=r[2],k=r[6],te=r[10],ne=r[14],re=r[3],ie=r[7],ae=r[11],oe=r[15];return i[0]=a*x+o*T+s*ee+c*re,i[4]=a*S+o*E+s*k+c*ie,i[8]=a*C+o*D+s*te+c*ae,i[12]=a*w+o*O+s*ne+c*oe,i[1]=l*x+u*T+d*ee+f*re,i[5]=l*S+u*E+d*k+f*ie,i[9]=l*C+u*D+d*te+f*ae,i[13]=l*w+u*O+d*ne+f*oe,i[2]=p*x+m*T+h*ee+g*re,i[6]=p*S+m*E+h*k+g*ie,i[10]=p*C+m*D+h*te+g*ae,i[14]=p*w+m*O+h*ne+g*oe,i[3]=_*x+v*T+y*ee+b*re,i[7]=_*S+v*E+y*k+b*ie,i[11]=_*C+v*D+y*te+b*ae,i[15]=_*w+v*O+y*ne+b*oe,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,ee=_*O-v*D+y*E+b*T-x*w+S*C;if(ee===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let k=1/ee;return e[0]=(o*O-s*D+c*E)*k,e[1]=(r*D-n*O-i*E)*k,e[2]=(m*S-h*x+g*b)*k,e[3]=(d*x-u*S-f*b)*k,e[4]=(s*T-a*O-c*w)*k,e[5]=(t*O-r*T+i*w)*k,e[6]=(h*y-p*S-g*v)*k,e[7]=(l*S-d*y+f*v)*k,e[8]=(a*D-o*T+c*C)*k,e[9]=(n*T-t*D-i*C)*k,e[10]=(p*x-m*y+g*_)*k,e[11]=(u*y-l*x-f*_)*k,e[12]=(o*w-a*E-s*C)*k,e[13]=(t*E-n*w+r*C)*k,e[14]=(m*v-p*b-h*_)*k,e[15]=(l*b-u*v+d*_)*k,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=Ei.set(r[0],r[1],r[2]).length(),o=Ei.set(r[4],r[5],r[6]).length(),s=Ei.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Di.copy(this);let c=1/a,l=1/o,u=1/s;return Di.elements[0]*=c,Di.elements[1]*=c,Di.elements[2]*=c,Di.elements[4]*=l,Di.elements[5]*=l,Di.elements[6]*=l,Di.elements[8]*=u,Di.elements[9]*=u,Di.elements[10]*=u,t.setFromRotationMatrix(Di),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=yr,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=yr,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}},Ei=new V,Di=new U,Oi=new V(0,0,0),ki=new V(1,1,1),Ai=new V,ji=new V,Mi=new V,Ni=new U,Pi=new B,Fi=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(R(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(-R(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(R(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(-R(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(R(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(-R(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:I(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Ni.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Ni,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Pi.setFromEuler(this),this.setFromQuaternion(Pi,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}};Fi.DEFAULT_ORDER=`XYZ`;var Ii=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}},Li=0,Ri=new V,zi=new B,Bi=new U,Vi=new V,Hi=new V,Ui=new V,Wi=new B,Gi=new V(1,0,0),Ki=new V(0,1,0),qi=new V(0,0,1),Ji={type:`added`},Yi={type:`removed`},Xi={type:`childadded`,child:null},Zi={type:`childremoved`,child:null},Qi=class e extends jr{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Li++}),this.uuid=Ir(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new V,n=new Fi,r=new B,i=new V(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 U},normalMatrix:{value:new H}}),this.matrix=new U,this.matrixWorld=new U,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ii,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 zi.setFromAxisAngle(e,t),this.quaternion.multiply(zi),this}rotateOnWorldAxis(e,t){return zi.setFromAxisAngle(e,t),this.quaternion.premultiply(zi),this}rotateX(e){return this.rotateOnAxis(Gi,e)}rotateY(e){return this.rotateOnAxis(Ki,e)}rotateZ(e){return this.rotateOnAxis(qi,e)}translateOnAxis(e,t){return Ri.copy(e).applyQuaternion(this.quaternion),this.position.add(Ri.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Gi,e)}translateY(e){return this.translateOnAxis(Ki,e)}translateZ(e){return this.translateOnAxis(qi,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Bi.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Vi.copy(e):Vi.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),Hi.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Bi.lookAt(Hi,Vi,this.up):Bi.lookAt(Vi,Hi,this.up),this.quaternion.setFromRotationMatrix(Bi),r&&(Bi.extractRotation(r.matrixWorld),zi.setFromRotationMatrix(Bi),this.quaternion.premultiply(zi.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(L(`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(Ji),Xi.child=e,this.dispatchEvent(Xi),Xi.child=null):L(`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(Yi),Zi.child=e,this.dispatchEvent(Zi),Zi.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),Bi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Bi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Bi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Ji),Xi.child=e,this.dispatchEvent(Xi),Xi.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(Hi,e,Ui),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Hi,Wi,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}};Qi.DEFAULT_UP=new V(0,1,0),Qi.DEFAULT_MATRIX_AUTO_UPDATE=!0,Qi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var $i=class extends Qi{constructor(){super(),this.isGroup=!0,this.type=`Group`}},ea={type:`move`},ta=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new $i,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 $i,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new V,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new V),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new $i,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new V,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new V,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(ea)))}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 $i;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},na={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},ra={h:0,s:0,l:0},ia={h:0,s:0,l:0};function aa(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 W=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=fr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ui.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=ui.workingColorSpace){return this.r=e,this.g=t,this.b=n,ui.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=ui.workingColorSpace){if(e=Lr(e,1),t=R(t,0,1),n=R(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=aa(i,r,e+1/3),this.g=aa(i,r,e),this.b=aa(i,r,e-1/3)}return ui.colorSpaceToWorking(this,r),this}setStyle(e,t=fr){function n(t){t!==void 0&&parseFloat(t)<1&&I(`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:I(`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);I(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=fr){let n=na[e.toLowerCase()];return n===void 0?I(`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=di(e.r),this.g=di(e.g),this.b=di(e.b),this}copyLinearToSRGB(e){return this.r=fi(e.r),this.g=fi(e.g),this.b=fi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=fr){return ui.workingToColorSpace(oa.copy(this),e),Math.round(R(oa.r*255,0,255))*65536+Math.round(R(oa.g*255,0,255))*256+Math.round(R(oa.b*255,0,255))}getHexString(e=fr){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ui.workingColorSpace){ui.workingToColorSpace(oa.copy(this),t);let n=oa.r,r=oa.g,i=oa.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=ui.workingColorSpace){return ui.workingToColorSpace(oa.copy(this),t),e.r=oa.r,e.g=oa.g,e.b=oa.b,e}getStyle(e=fr){ui.workingToColorSpace(oa.copy(this),e);let t=oa.r,n=oa.g,r=oa.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(ra),this.setHSL(ra.h+e,ra.s+t,ra.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(ra),e.getHSL(ia);let n=Br(ra.h,ia.h,t),r=Br(ra.s,ia.s,t),i=Br(ra.l,ia.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}},oa=new W;W.NAMES=na;var sa=class e{constructor(e,t=1,n=1e3){this.isFog=!0,this.name=``,this.color=new W(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}}},ca=class extends Qi{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 Fi,this.environmentIntensity=1,this.environmentRotation=new Fi,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}},la=new V,ua=new V,da=new V,fa=new V,pa=new V,ma=new V,ha=new V,ga=new V,_a=new V,va=new V,ya=new xi,ba=new xi,xa=new xi,Sa=class e{constructor(e=new V,t=new V,n=new V){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),la.subVectors(e,t),r.cross(la);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){la.subVectors(r,t),ua.subVectors(n,t),da.subVectors(e,t);let a=la.dot(la),o=la.dot(ua),s=la.dot(da),c=ua.dot(ua),l=ua.dot(da),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,fa)===null?!1:fa.x>=0&&fa.y>=0&&fa.x+fa.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,fa)===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,fa.x),s.addScaledVector(a,fa.y),s.addScaledVector(o,fa.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return ya.setScalar(0),ba.setScalar(0),xa.setScalar(0),ya.fromBufferAttribute(e,t),ba.fromBufferAttribute(e,n),xa.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(ya,i.x),a.addScaledVector(ba,i.y),a.addScaledVector(xa,i.z),a}static isFrontFacing(e,t,n,r){return la.subVectors(n,t),ua.subVectors(e,t),la.cross(ua).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 la.subVectors(this.c,this.b),ua.subVectors(this.a,this.b),la.cross(ua).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;pa.subVectors(r,n),ma.subVectors(i,n),ga.subVectors(e,n);let s=pa.dot(ga),c=ma.dot(ga);if(s<=0&&c<=0)return t.copy(n);_a.subVectors(e,r);let l=pa.dot(_a),u=ma.dot(_a);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(pa,a);va.subVectors(e,i);let f=pa.dot(va),p=ma.dot(va);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(ma,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return ha.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(ha,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(pa,a).addScaledVector(ma,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Ca=class{constructor(e=new V(1/0,1/0,1/0),t=new V(-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(Ta.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ta.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=Ta.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,Ta):Ta.fromBufferAttribute(r,t),Ta.applyMatrix4(e.matrixWorld),this.expandByPoint(Ta);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Ea.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Ea.copy(e.boundingBox)),Ea.applyMatrix4(e.matrixWorld),this.union(Ea)}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,Ta),Ta.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(Na),Pa.subVectors(this.max,Na),Da.subVectors(e.a,Na),Oa.subVectors(e.b,Na),ka.subVectors(e.c,Na),Aa.subVectors(Oa,Da),ja.subVectors(ka,Oa),Ma.subVectors(Da,ka);let t=[0,-Aa.z,Aa.y,0,-ja.z,ja.y,0,-Ma.z,Ma.y,Aa.z,0,-Aa.x,ja.z,0,-ja.x,Ma.z,0,-Ma.x,-Aa.y,Aa.x,0,-ja.y,ja.x,0,-Ma.y,Ma.x,0];return!La(t,Da,Oa,ka,Pa)||(t=[1,0,0,0,1,0,0,0,1],!La(t,Da,Oa,ka,Pa))?!1:(Fa.crossVectors(Aa,ja),t=[Fa.x,Fa.y,Fa.z],La(t,Da,Oa,ka,Pa))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ta).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ta).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:(wa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wa),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}},wa=[new V,new V,new V,new V,new V,new V,new V,new V],Ta=new V,Ea=new Ca,Da=new V,Oa=new V,ka=new V,Aa=new V,ja=new V,Ma=new V,Na=new V,Pa=new V,Fa=new V,Ia=new V;function La(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ia.fromArray(e,a);let o=i.x*Math.abs(Ia.x)+i.y*Math.abs(Ia.y)+i.z*Math.abs(Ia.z),s=t.dot(Ia),c=n.dot(Ia),l=r.dot(Ia);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Ra=za();function za(){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 Ba(e){Math.abs(e)>65504&&I(`DataUtils.toHalfFloat(): Value out of range.`),e=R(e,-65504,65504),Ra.floatView[0]=e;let t=Ra.uint32View[0],n=t>>23&511;return Ra.baseTable[n]+((t&8388607)>>Ra.shiftTable[n])}function Va(e){let t=e>>10;return Ra.uint32View[0]=Ra.mantissaTable[Ra.offsetTable[t]+(e&1023)]+Ra.exponentTable[t],Ra.floatView[0]}var Ha=class{static toHalfFloat(e){return Ba(e)}static fromHalfFloat(e){return Va(e)}},Ua=new V,Wa=new z,Ga=0,G=class extends jr{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:Ga++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=_r,this.updateRanges=[],this.gpuType=Qt,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++)Wa.fromBufferAttribute(this,t),Wa.applyMatrix3(e),this.setXY(t,Wa.x,Wa.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyMatrix3(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyMatrix4(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyNormalMatrix(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.transformDirection(e),this.setXYZ(t,Ua.x,Ua.y,Ua.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=ti(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ni(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ti(t,this.array)),t}setX(e,t){return this.normalized&&(t=ni(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ti(t,this.array)),t}setY(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}setW(e,t){return this.normalized&&(t=ni(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ni(t,this.array),n=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(r,this.array),i=ni(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`})}},Ka=class extends G{constructor(e,t,n){super(new Uint16Array(e),t,n)}},qa=class extends G{constructor(e,t,n){super(new Uint32Array(e),t,n)}},Ja=class extends G{constructor(e,t,n){super(new Float32Array(e),t,n)}},Ya=new Ca,Xa=new V,Za=new V,Qa=class{constructor(e=new V,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?Ya.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;Xa.subVectors(e,this.center);let t=Xa.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Xa,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):(Za.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Xa.copy(e.center).add(Za)),this.expandByPoint(Xa.copy(e.center).sub(Za))),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}},$a=0,eo=new U,to=new Qi,no=new V,ro=new Ca,io=new Ca,ao=new V,K=class e extends jr{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:$a++}),this.uuid=Ir(),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(br(e)?qa:Ka)(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 H().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 eo.makeRotationFromQuaternion(e),this.applyMatrix4(eo),this}rotateX(e){return eo.makeRotationX(e),this.applyMatrix4(eo),this}rotateY(e){return eo.makeRotationY(e),this.applyMatrix4(eo),this}rotateZ(e){return eo.makeRotationZ(e),this.applyMatrix4(eo),this}translate(e,t,n){return eo.makeTranslation(e,t,n),this.applyMatrix4(eo),this}scale(e,t,n){return eo.makeScale(e,t,n),this.applyMatrix4(eo),this}lookAt(e){return to.lookAt(e),to.updateMatrix(),this.applyMatrix4(to.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(no).negate(),this.translate(no.x,no.y,no.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 Ja(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&&I(`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 Ca);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){L(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new V(-1/0,-1/0,-1/0),new V(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];ro.setFromBufferAttribute(n),this.morphTargetsRelative?(ao.addVectors(this.boundingBox.min,ro.min),this.boundingBox.expandByPoint(ao),ao.addVectors(this.boundingBox.max,ro.max),this.boundingBox.expandByPoint(ao)):(this.boundingBox.expandByPoint(ro.min),this.boundingBox.expandByPoint(ro.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&L(`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 Qa);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){L(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new V,1/0);return}if(e){let n=this.boundingSphere.center;if(ro.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];io.setFromBufferAttribute(n),this.morphTargetsRelative?(ao.addVectors(ro.min,io.min),ro.expandByPoint(ao),ao.addVectors(ro.max,io.max),ro.expandByPoint(ao)):(ro.expandByPoint(io.min),ro.expandByPoint(io.max))}ro.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)ao.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(ao));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++)ao.fromBufferAttribute(a,t),o&&(no.fromBufferAttribute(e,t),ao.add(no)),r=Math.max(r,n.distanceToSquared(ao))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&L(`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){L(`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 G(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new V,s[e]=new V;let c=new V,l=new V,u=new V,d=new z,f=new z,p=new z,m=new V,h=new V;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 V,y=new V,b=new V,x=new V;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 G(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 V,i=new V,a=new V,o=new V,s=new V,c=new V,l=new V,u=new V;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++)ao.fromBufferAttribute(e,t),ao.normalize(),e.setXYZ(t,ao.x,ao.y,ao.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 G(a,r,i)}if(this.index===null)return I(`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`})}},oo=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=_r,this.updateRanges=[],this.version=0,this.uuid=Ir()}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=Ir()),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=Ir()),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}}},so=new V,co=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++)so.fromBufferAttribute(this,t),so.applyMatrix4(e),this.setXYZ(t,so.x,so.y,so.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)so.fromBufferAttribute(this,t),so.applyNormalMatrix(e),this.setXYZ(t,so.x,so.y,so.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)so.fromBufferAttribute(this,t),so.transformDirection(e),this.setXYZ(t,so.x,so.y,so.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=ti(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ni(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=ti(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=ti(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=ti(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ni(t,this.array),n=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(r,this.array),i=ni(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){Er(`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 G(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){Er(`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}}},lo=0,uo=class extends jr{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:lo++}),this.uuid=Ir(),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 W(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=gr,this.stencilZFail=gr,this.stencilZPass=gr,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){I(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){I(`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++}},fo=new V,po=new V,mo=new V,ho=new V,go=new V,_o=new V,vo=new V,yo=class{constructor(e=new V,t=new V(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,fo)),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=fo.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(fo.copy(this.origin).addScaledVector(this.direction,t),fo.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){po.copy(e).add(t).multiplyScalar(.5),mo.copy(t).sub(e).normalize(),ho.copy(this.origin).sub(po);let i=e.distanceTo(t)*.5,a=-this.direction.dot(mo),o=ho.dot(this.direction),s=-ho.dot(mo),c=ho.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(po).addScaledVector(mo,d),f}intersectSphere(e,t){fo.subVectors(e.center,this.origin);let n=fo.dot(this.direction),r=fo.dot(fo)-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,fo)!==null}intersectTriangle(e,t,n,r,i){go.subVectors(t,e),_o.subVectors(n,e),vo.crossVectors(go,_o);let a=this.direction.dot(vo),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;ho.subVectors(this.origin,e);let s=o*this.direction.dot(_o.crossVectors(ho,_o));if(s<0)return null;let c=o*this.direction.dot(go.cross(ho));if(c<0||s+c>a)return null;let l=-o*ho.dot(vo);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)}},bo=class extends uo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new W(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 Fi,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}},xo=new U,So=new yo,Co=new Qa,wo=new V,To=new V,Eo=new V,Do=new V,Oo=new V,ko=new V,Ao=new V,jo=new V,Mo=class extends Qi{constructor(e=new K,t=new bo){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){ko.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Oo.fromBufferAttribute(s,e),a?ko.addScaledVector(Oo,r):ko.addScaledVector(Oo.sub(t),r))}t.add(ko)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Co.copy(n.boundingSphere),Co.applyMatrix4(i),So.copy(e.ray).recast(e.near),!(Co.containsPoint(So.origin)===!1&&(So.intersectSphere(Co,wo)===null||So.origin.distanceToSquared(wo)>(e.far-e.near)**2))&&(xo.copy(i).invert(),So.copy(e.ray).applyMatrix4(xo),!(n.boundingBox!==null&&So.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,So)))}_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=Po(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=Po(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=Po(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=Po(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function No(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;jo.copy(s),jo.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(jo);return l<n.near||l>n.far?null:{distance:l,point:jo.clone(),object:e}}function Po(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,To),e.getVertexPosition(c,Eo),e.getVertexPosition(l,Do);let u=No(e,t,n,r,To,Eo,Do,Ao);if(u){let e=new V;Sa.getBarycoord(Ao,To,Eo,Do,e),i&&(u.uv=Sa.getInterpolatedAttribute(i,s,c,l,e,new z)),a&&(u.uv1=Sa.getInterpolatedAttribute(a,s,c,l,e,new z)),o&&(u.normal=Sa.getInterpolatedAttribute(o,s,c,l,e,new V),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new V,materialIndex:0};Sa.getNormal(To,Eo,Do,t.normal),u.face=t,u.barycoord=e}return u}var Fo=new xi,Io=new xi,Lo=new xi,Ro=new xi,zo=new U,Bo=new V,Vo=new Qa,Ho=new U,Uo=new yo,Wo=class extends Mo{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=It,this.bindMatrix=new U,this.bindMatrixInverse=new U,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ca),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Bo),this.boundingBox.expandByPoint(Bo)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Qa),this.boundingSphere.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Bo),this.boundingSphere.expandByPoint(Bo)}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(),Vo.copy(this.boundingSphere),Vo.applyMatrix4(r),e.ray.intersectsSphere(Vo)!==!1&&(Ho.copy(r).invert(),Uo.copy(e.ray).applyMatrix4(Ho),!(this.boundingBox!==null&&Uo.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,Uo)))}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 xi,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():I(`SkinnedMesh: Unrecognized bindMode: `+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;Io.fromBufferAttribute(r.attributes.skinIndex,e),Lo.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?(Fo.copy(t),t.set(0,0,0,0)):(Fo.set(...t,1),t.set(0,0,0)),Fo.applyMatrix4(this.bindMatrix);for(let e=0;e<4;e++){let r=Lo.getComponent(e);if(r!==0){let i=Io.getComponent(e);zo.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(Ro.copy(Fo).applyMatrix4(zo),r)}}return t.isVector4&&(t.w=Fo.w),t.applyMatrix4(this.bindMatrixInverse)}},Go=class extends Qi{constructor(){super(),this.isBone=!0,this.type=`Bone`}},Ko=class extends bi{constructor(e=null,t=1,n=1,r,i,a,o,s,c=Bt,l=Bt,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}},qo=new U,Jo=new U,Yo=class e{constructor(e=[],t=[]){this.uuid=Ir(),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){I(`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 U)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let t=new U;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:Jo;qo.multiplyMatrices(i,t[r]),qo.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 Ko(t,e,e,cn,Qt);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&&(I(`Skeleton: No bone found with UUID:`,r),i=new Go),this.bones.push(i),this.boneInverses.push(new U().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}},Xo=class extends G{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}},Zo=new U,Qo=new U,$o=[],es=new Ca,ts=new U,ns=new Mo,rs=new Qa,is=class extends Mo{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Xo(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,ts)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Ca),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zo),es.copy(e.boundingBox).applyMatrix4(Zo),this.boundingBox.union(es)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Qa),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zo),rs.copy(e.boundingSphere).applyMatrix4(Zo),this.boundingSphere.union(rs)}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(ns.geometry=this.geometry,ns.material=this.material,ns.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),rs.copy(this.boundingSphere),rs.applyMatrix4(n),e.ray.intersectsSphere(rs)!==!1))for(let i=0;i<r;i++){this.getMatrixAt(i,Zo),Qo.multiplyMatrices(n,Zo),ns.matrixWorld=Qo,ns.raycast(e,$o);for(let e=0,n=$o.length;e<n;e++){let n=$o[e];n.instanceId=i,n.object=this,t.push(n)}$o.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new Xo(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 Ko(new Float32Array(r*this.count),r,this.count,dn,Qt));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)}},as=new V,os=new V,ss=new H,cs=class{constructor(e=new V(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=as.subVectors(n,t).cross(os.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(as),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||ss.getNormalMatrix(e),r=this.coplanarPoint(as).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)}},ls=new Qa,us=new z(.5,.5),ds=new V,fs=class{constructor(e=new cs,t=new cs,n=new cs,r=new cs,i=new cs,a=new cs){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=yr,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(),ls.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ls.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ls)}intersectsSprite(e){return ls.center.set(0,0,0),ls.radius=.7071067811865476+us.distanceTo(e.center),ls.applyMatrix4(e.matrixWorld),this.intersectsSphere(ls)}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(ds.x=r.normal.x>0?e.max.x:e.min.x,ds.y=r.normal.y>0?e.max.y:e.min.y,ds.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(ds)<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)}},ps=class extends uo{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new W(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}},ms=new V,hs=new V,gs=new U,_s=new yo,vs=new Qa,ys=new V,bs=new V,xs=class extends Qi{constructor(e=new K,t=new ps){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++)ms.fromBufferAttribute(t,e-1),hs.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=ms.distanceTo(hs);e.setAttribute(`lineDistance`,new Ja(n,1))}else I(`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(),vs.copy(n.boundingSphere),vs.applyMatrix4(r),vs.radius+=i,e.ray.intersectsSphere(vs)===!1)return;gs.copy(r).invert(),_s.copy(e.ray).applyMatrix4(gs);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=Ss(this,e,_s,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=Ss(this,e,_s,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=Ss(this,e,_s,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=Ss(this,e,_s,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 Ss(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(ms.fromBufferAttribute(s,i),hs.fromBufferAttribute(s,a),n.distanceSqToSegment(ms,hs,ys,bs)>r)return;ys.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(ys);if(!(c<t.near||c>t.far))return{distance:c,point:bs.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Cs=new V,ws=new V,Ts=class extends xs{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)Cs.fromBufferAttribute(t,e),ws.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+Cs.distanceTo(ws);e.setAttribute(`lineDistance`,new Ja(n,1))}else I(`LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Es=class extends xs{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type=`LineLoop`}},Ds=class extends uo{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new W(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}},Os=new U,ks=new yo,As=new Qa,js=new V,Ms=class extends Qi{constructor(e=new K,t=new Ds){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(),As.copy(n.boundingSphere),As.applyMatrix4(r),As.radius+=i,e.ray.intersectsSphere(As)===!1)return;Os.copy(r).invert(),ks.copy(e.ray).applyMatrix4(Os);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);js.fromBufferAttribute(l,n),Ns(js,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++)js.fromBufferAttribute(l,a),Ns(js,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 Ns(e,t,n,r,i,a,o){let s=ks.distanceSqToPoint(e);if(s<n){let n=new V;ks.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 Ps=class extends bi{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}},Fs=class extends bi{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}},Is=class extends bi{constructor(e,t,n=Zt,r,i,a,o=Bt,s=Bt,c,l=ln,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 gi(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}},Ls=class extends Is{constructor(e,t=Zt,n=301,r,i,a=Bt,o=Bt,s,c=ln){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}},Rs=class extends bi{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},zs=class e extends K{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 Ja(c,3)),this.setAttribute(`normal`,new Ja(l,3)),this.setAttribute(`uv`,new Ja(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 V;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)}},Bs=class e extends K{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 V,g=new V;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 Ja(o,3)),this.setAttribute(`normal`,new Ja(s,3)),this.setAttribute(`uv`,new Ja(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)}},Vs=class e extends K{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 Ja(u,3)),this.setAttribute(`normal`,new Ja(d,3)),this.setAttribute(`uv`,new Ja(f,2));function _(){let a=new V,_=new V,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 z,m=new V,_=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)}},Hs=class e extends Vs{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)}},Us=class e extends K{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 Ja(i,3)),this.setAttribute(`normal`,new Ja(i.slice(),3)),this.setAttribute(`uv`,new Ja(a,2)),r===0?this.computeVertexNormals():this.normalizeNormals();function o(e){let n=new V,r=new V,i=new V;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 V;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 V;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 V,t=new V,n=new V,r=new V,o=new z,s=new z,c=new z;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)}},Ws=class e extends Us{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)}},Gs=class e extends K{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 Ja(p,3)),this.setAttribute(`normal`,new Ja(m,3)),this.setAttribute(`uv`,new Ja(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)}},Ks=class e extends K{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 V,d=new V,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 Ja(p,3)),this.setAttribute(`normal`,new Ja(m,3)),this.setAttribute(`uv`,new Ja(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 qs(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(Ys(i))i.isRenderTargetTexture?(I(`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(Ys(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 Js(e){let t={};for(let n=0;n<e.length;n++){let r=qs(e[n]);for(let e in r)t[e]=r[e]}return t}function Ys(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function Xs(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Zs(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:ui.workingColorSpace}var Qs={clone:qs,merge:Js},$s=`void main() {
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=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}},n=class{changed=new t;_master=1;_sfx=1;_music=1;_muted=!1;get master(){return this._master}set master(e){this._master=this.assign(this._master,e)}get sfx(){return this._sfx}set sfx(e){this._sfx=this.assign(this._sfx,e)}get music(){return this._music}set music(e){this._music=this.assign(this._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*r(t)}assign(e,t){if(!Number.isFinite(t))return e;let n=r(t);return n!==e&&this.changed.emit(),n}};function r(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}function i(e,t,n){let r=o(e,t);return n===`in`?r:1-r}function a(e,t){let n=o(e,t)*Math.PI/2;return{out:s(Math.cos(n)),in:s(Math.sin(n))}}function o(e,t){return!Number.isFinite(e)||t<=0?1:s(e/t)}function s(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var c=null,l=null;function u(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function d(){if(c)return c();let e=u();return e?new e:null}function f(){return l?l():typeof Audio>`u`?null:new Audio}var p={src:``,setGain(){},setLoop(){},play(){},stop(){}},m=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}},h=class{ctx=null;resolved=!1;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=d(),!0),this.ctx}createTrack(e){let t=this.ensure(),n=f();return!t||!n?{...p,src:e}:(t.state===`suspended`&&t.resume(),new m(e,n,t))}unlock(){let e=this.ensure();e&&e.state===`suspended`&&e.resume()}},g=null,_=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=g?g(this.buses):new h;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=v(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=a(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`?i(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`?i(this.outgoing.t,this.outgoing.duration,`out`):0;this.outgoing.track.setGain(e*t)}}killOutgoing(){this.outgoing?.track.stop(),this.outgoing=null}};function v(e){return Number.isFinite(e)?e<0?0:e>1?1:e:0}var y=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`IncantoError`,this.code=e,this.details=n}},b=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 y(`BAD_FORMAT`,`Rng.pick needs a non-empty array.`);return e[this.int(0,e.length-1)]}},x={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}},S=Object.keys(x),C=Math.PI*2;function w(e,t={}){let n=t.sampleRate??44100,r=t.pitch??1,i=new b((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(C*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(C*d);break;default:p-=m/n,p<=0&&(f=i.range(-1,1),p+=1),h=f;break}s[t]=T(h*o*e.volume)}return s}function T(e){return e<-1?-1:e>1?1:e}var E=[`inverse`,`linear`,`exponential`];function D(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=O(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)?k(o):0}function O(e,t,n){return e<t?t:e>n?n:e}function k(e){return e<0?0:e>1?1:e}var A={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}},ee={set:()=>{},stop:()=>{},stopped:!0};function te(e,t,n){let r=A[t]??A.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 ne=ee;function re(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 ie(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 ae=null;function oe(){let e=globalThis;return e.AudioContext??e.webkitAudioContext??null}function se(){if(ae)return ae();let e=oe();return e?new e:null}function ce(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 le=class{ctx=null;resolved=!1;pcmCache=new Map;get available(){return this.ensure()!==null}ensure(){return this.resolved||=(this.ctx=se(),!0),this.ctx}startVoice(e,t=1){let n=this.ensure();return n?(n.state===`suspended`&&n.resume(),te(n,e,t)):ne}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=ce(e,a,i),s=this.pcmCache.get(o);s||(s=w(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,ie(t,e.position),r.listener&&re(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 ue(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 de(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>de(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&&de(e[n],t[n]))}return!1}function j(e){return typeof e!=`object`||!e?e:JSON.parse(JSON.stringify(e))}function fe(e,t,n){let r=ue(t);if(r===`null`)return;let i=ue(e);if(i!==r)throw new y(`PROP_TYPE_MISMATCH`,`Prop '${n}' expects ${r} (default ${JSON.stringify(t)}), got ${i} (${JSON.stringify(e)}).`,{prop:n});if(typeof e==`number`&&!Number.isFinite(e))throw new y(`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 y(`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++)fe(e[r],t[r],`${n}[${r}]`)}}var pe=new Map;function M(e,t){let n=pe.get(e.typeName);if(n&&n!==e&&!t?.replace)throw new y(`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});pe.set(e.typeName,e)}function me(e){let t=pe.get(e);if(!t){let t=[...pe.keys()];throw new y(`UNKNOWN_NODE_TYPE`,`Unknown node type '${e}'. Registered types: [${t.join(`, `)}].`,{nodeType:e,validOptions:t})}return t}function he(){return[...pe.keys()]}function ge(e){return ve(me(e))}function _e(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 ve(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 ye(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 be(e,t,n,r,i={}){for(let[n,r]of Object.entries(t))e[n]=j(r.default);if(n)for(let[a,o]of Object.entries(n)){let n=t[a]?a:i[a]??a,s=t[n];if(!s){let e=Object.keys(t);throw new y(`UNKNOWN_PROP`,`Unknown prop '${a}' on '${r}'. Valid props: [${e.join(`, `)}].`,{prop:a,nodeType:r,validOptions:e})}fe(o,s.default,`${r}.${n}`),e[n]=j(o)}}function xe(e,t){let n=me(e),r=new n;return be(r,ge(e),t,e,ye(n)),r}var N=class{static props;static signals;node;get engine(){let e=this.node?.tree?.engine;if(!e)throw new y(`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)}},Se=class extends N{},Ce=new Map;function we(e){return Ce.has(e)}function P(e){let t=Ce.get(e);if(!t){let t=[...Ce.keys()];throw new y(`UNKNOWN_BEHAVIOR`,`Unknown behavior '${e}'. Registered behaviors: [${t.join(`, `)}]. Did you forget registerBehavior('${e}', ${e})?`,{validOptions:t})}return t}function Te(e,t){let n=P(e),r=new n;return be(r,ve(n),t,`script:${e}`),r}var F=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 Ee(e){let t=e;return!!t&&(t.isContentEditable===!0||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`)}var De=class{actions=new Map;down=new Set;pressedEdge=new Set;releasedEdge=new Set;detach=null;declare(e){for(let[t,n]of Object.entries(e)){let e=n;if(e.type===`button`){let n=e.keys;if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new y(`BAD_FORMAT`,`Input action '${t}': button "keys" must be an array of KeyboardEvent.code strings.`);if(e.touch!==void 0&&e.touch!==`button`)throw new y(`BAD_FORMAT`,`Input action '${t}': button "touch" must be 'button', got ${JSON.stringify(e.touch)}.`);this.actions.set(t,{type:`button`,keys:[...n],...e.touch===`button`?{touch:`button`}:{}})}else if(e.type===`vector2`){let n=e.keys;for(let e of[`up`,`down`,`left`,`right`])if(!Array.isArray(n?.[e]))throw new y(`BAD_FORMAT`,`Input action '${t}': vector2 "keys" needs arrays for up/down/left/right.`);if(e.touch!==void 0&&e.touch!==`joystick`)throw new y(`BAD_FORMAT`,`Input action '${t}': vector2 "touch" must be 'joystick', got ${JSON.stringify(e.touch)}.`);let r=n;this.actions.set(t,{type:`vector2`,keys:{up:[...r.up],down:[...r.down],left:[...r.left],right:[...r.right]},...e.touch===`joystick`?{touch:`joystick`}:{}})}else throw new y(`BAD_FORMAT`,`Input action '${t}': "type" must be 'button' or 'vector2', got ${JSON.stringify(e.type)}.`)}}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 y(`BAD_FORMAT`,`Input action '${e}' is a button — use pressAction/releaseAction, not setActionVector.`);if(!Number.isFinite(t)||!Number.isFinite(n))throw new y(`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.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=>{(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=>{Ee(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=>{Ee(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)}getVector(e){let t=this.get(e);if(t.type!==`vector2`)throw new y(`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 y(`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 y(`BAD_FORMAT`,`Input action '${e}' is a vector2 — use getVector, not button queries.`);return t}},Oe=class{added=new t;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)}},ke=.25;function Ae(e){let t=!0,n=requestAnimationFrame(function r(i){t&&(e(i),n=requestAnimationFrame(r))});return()=>{t=!1,cancelAnimationFrame(n)}}var je=class{updated=new t;fixedUpdated=new t;sceneChanged=new t;input=new De;rng;log=new Oe;audio=new n;sfx=new le;music=new _(this.audio);fixedStep;maxFixedSteps;scheduler;_scene=null;lastMs=null;accumulator=0;disposeScheduler=null;frameStats=new F;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??Ae,this.rng=new b(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),this.sceneChanged.emit(e))}start(){this.disposeScheduler||=this.scheduler(e=>this.tick(e))}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?Me(this._scene.tree.root):0,running:this.disposeScheduler!==null}}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.min((e-this.lastMs)/1e3,ke),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 Me(e){let t=1;for(let n of e.children)t+=Me(n);return t}function Ne(e){if(e===``)throw new y(`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 y(`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 y(`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 y(`BAD_NODE_PATH`,`Invalid node path '${e}'. '%' is only allowed as a whole-path prefix ('%Name').`);if(t===`.`)throw new y(`BAD_NODE_PATH`,`Invalid node path '${e}'. '.' is only valid as the whole path — drop the './' prefix.`)}if(t&&r.includes(`..`))throw new y(`BAD_NODE_PATH`,`Invalid node path '${e}'. Absolute paths must not contain '..'.`);return{kind:t?`absolute`:`relative`,segments:r}}function Pe(e){if(e===``||e.includes(`/`)||e.includes(`%`))throw new y(`TREE_VIOLATION`,`Invalid node name '${e}'. Names must be non-empty and must not contain '/' or '%'.`)}var Fe=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,Pe(this._name)}get name(){return this._name}set name(e){Pe(e);let t=this._name;this._parent?this._name=Le(e,this._parent._children,this):this._name=e,this._tree&&this._name!==t&&(this._tree._unindexName(this,t),this._tree._indexName(this))}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 y(`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 y(`TREE_VIOLATION`,`Cannot add '${e.name}' to '${this.name}': it is this node or an ancestor (cycle).`);return e._name=Le(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 y(`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 y(`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=Ne(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 y(`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(Ie(this.getRoot(),t.name,n),n.length>1)throw new y(`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 y(`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 n=this._signals.get(e);return n||(n=new t,this._signals.set(e,n)),n}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){this.update(e),this.behavior?.update?.(e);let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateUpdate(e)}_propagateFixedUpdate(e){this.fixedUpdate(e),this.behavior?.fixedUpdate?.(e);let t=this._children;for(let n=0,r=t.length;n<r;n++)t[n]?._propagateFixedUpdate(e)}onEnterTree(){}onReady(){}onExitTree(){}update(e){}fixedUpdate(e){}};function Ie(e,t,n){e.name===t&&n.push(e);for(let r of e.children)Ie(r,t,n)}function Le(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 Re=null;function ze(){return Re?Re():typeof Audio>`u`?null:new Audio}var Be=class extends Fe{static typeName=`AudioPlayer`;static signals=[`finished`];static props={src:{default:``},preset:{default:`custom`,options:[`custom`,...S]},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:[...E]}};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`&&!S.includes(t.preset))throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' preset must be 'custom' or one of [${S.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:S});if(t.bus!==`sfx`&&t.bus!==`music`)throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' bus must be 'sfx' or 'music', got '${t.bus}'.`,{prop:`bus`,validOptions:[`sfx`,`music`]});if(!E.includes(t.rolloff))throw new y(`BAD_FORMAT`,`AudioPlayer '${e.name}' rolloff must be one of [${E.join(`, `)}], got '${t.rolloff}'.`,{prop:`rolloff`,validOptions:[...E]})}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 D(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=ze(),!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=x[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)}},Ve={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;`},He=`600 14px system-ui, -apple-system, 'Segoe UI', sans-serif`;function Ue(){return typeof document<`u`}var We=class extends Fe{static typeName=`HudLayer`;static props={zIndex:{default:100},visible:{default:!0}};zIndex=100;visible=!0;_element=null;slots=new Map;onEnterTree(){if(!Ue())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:${He};`,document.body.appendChild(e),this._element=e}onExitTree(){this._element?.remove(),this._element=null,this.slots.clear()}update(){this._element&&(this._element.style.display=this.visible?``:`none`)}_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;${Ve[e]??Ve.topLeft}`,this._element.appendChild(t),this.slots.set(e,t)),t}},Ge=class extends Fe{static props={anchor:{default:`topLeft`,options:[`topLeft`,`top`,`topRight`,`left`,`center`,`right`,`bottomLeft`,`bottom`,`bottomRight`]},visible:{default:!0}};anchor=`topLeft`;visible=!0;_element=null;layer(){for(let e=this.parent;e;e=e.parent)if(e instanceof We)return e;return null}onReady(){if(!Ue())return;let e=this.layer()?._slot(this.anchor);e&&(this._element=this._build(),e.appendChild(this._element))}onExitTree(){this._element?.remove(),this._element=null}update(e){this._element&&(this._element.style.display=this.visible?``:`none`,this._sync())}_sync(){}},Ke=class extends Ge{static typeName=`UiText`;static props={...Ge.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(){this.text!==this.last&&this._element&&(this.last=this.text,this._element.textContent=this.text)}},qe=class extends Ge{static typeName=`UiBar`;static props={...Ge.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;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.textContent=this.label,t.style.cssText=`color:#fff;font-size:12px;text-shadow:0 1px 3px rgba(0,0,0,.7);`,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.ratio;e===this.lastRatio||!this.fill||(this.lastRatio=e,this.fill.style.width=`${e*100}%`,this.fill.style.background=e<=this.lowThreshold?this.lowColor:this.color)}},Je=class extends Ge{static typeName=`UiBanner`;static signals=[`bannerShown`];static props={...Ge.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.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))}},Ye=class extends Ge{static typeName=`UiButton`;static signals=[`pressed`];static props={...Ge.props,text:{default:`OK`},size:{default:16},color:{default:`#ffffff`},background:{default:`rgba(255,255,255,0.14)`},disabled:{default:!1}};text=`OK`;size=16;color=`#ffffff`;background=`rgba(255,255,255,0.14)`;disabled=!1;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(){this._element&&(this.text!==this.lastText&&(this.lastText=this.text,this._element.textContent=this.text),this._element.disabled=this.disabled,this._element.style.opacity=this.disabled?`0.45`:`1`)}},Xe=class extends Ge{static typeName=`UiDialogue`;static signals=[`lineShown`,`choiceMade`,`dialogueFinished`];static props={...Ge.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.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)})}},Ze=class extends Fe{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}}},Qe=.5*(Math.sqrt(3)-1),$e=(3-Math.sqrt(3))/6,et=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,0,1,0,-1]);function tt(e){let t=new b(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)*Qe,i=Math.floor(e+r),a=Math.floor(t+r),o=(i+a)*$e,s=e-(i-o),c=t-(a-o),l=+(s>c),u=s>c?0:1,d=s-l+$e,f=c-u+$e,p=s-1+2*$e,m=c-1+2*$e,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*(et[e]*s+et[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*(et[e]*d+et[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*(et[e]*p+et[e+1]*m)}return 70*_}}var nt={background:-2e3,terrain:-1e3,default:0,characters:1e3,effects:2e3,overlay:3e3};function rt(e,t){return(nt[e]??0)+t}var it={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`}},at=Object.keys(it);function ot(e,t,n){if(t===`custom`)return;let r=it[t];if(r)for(let[t,i]of Object.entries(r)){let r=n[t]?.default,a=e[t];r!==void 0&&de(a,r)&&(e[t]=Array.isArray(i)?[...i]:i)}}var st=9,ct=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)*st)}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*st,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*st,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*st,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*st,t*st,t*st+st),this.alive=t}};function lt(){M(Fe),M(Ze),M(Be),M(We),M(Ke),M(qe),M(Je),M(Ye),M(Xe)}function ut(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}}var dt=`@const`;function ft(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 pt(e,t){if(e==null)return e;if(ft(e)){let n=e[dt];if(!t||!(n in t)){let e=t?Object.keys(t):[];throw new y(`UNKNOWN_CONSTANT`,`Unknown constant '@const: ${n}'. Declared constants: ${e.length?e.join(`, `):`(none — add a "constants" section)`}.`)}return j(t[n])}if(Array.isArray(e))return e.map(e=>pt(e,t));if(typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=pt(i,t);return n}return e}var mt=class{_root=null;_engine=null;freeQueue=new Set;_nameIndex=new Map;_structureVersion=0;_frameId=0;get frameId(){return this._frameId}_indexName(e){this._structureVersion++;let t=this._nameIndex.get(e.name);t||(t=new Set,this._nameIndex.set(e.name,t)),t.add(e)}_unindexName(e,t=e.name){this._structureVersion++;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 y(`TREE_VIOLATION`,`SceneTree already has a root.`);if(e.parent)throw new y(`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&&ht(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 ht(e,t,n){e.isInGroup(t)&&n.push(e);for(let r of e.children)ht(r,t,n)}var gt=[`expand`,`letterbox`,`integer`];function _t(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 y(`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`||!gt.includes(n))throw new y(`BAD_FORMAT`,`Scene "viewport.fit" must be one of [${gt.join(`, `)}], got ${JSON.stringify(n)}.`);return{design:[t[0],t[1]],fit:n}}function vt(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 yt(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=j(e.tags));let r=ge(t.typeName),i={};for(let[t,n]of Object.entries(r)){let r=e[t];r!==void 0&&(bt(r,`${e.name}.${t}`),de(r,n.default)||(i[t]=j(r)))}return Object.keys(i).length>0&&(n.props=i),e.script&&(n.script=j(e.script)),e.network&&(n.network=j(e.network)),e.children.length>0&&(n.children=e.children.map(e=>yt(e))),n}function bt(e,t){if(typeof e==`number`&&!Number.isFinite(e))throw new y(`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++)bt(e[n],`${t}[${n}]`);else if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e))bt(r,`${t}.${n}`)}var xt=class{name;dimension;root;tree;environment;assets;constants;input;physics;multiplayer;viewport;connections;source;constructor(e,t,n){this.source=j(e),this.name=e.name,this.dimension=e.dimension,this.root=t,this.tree=n,this.assets=e.assets?j(e.assets):void 0,this.constants=e.constants?j(e.constants):void 0,this.input=e.input?j(e.input):void 0,this.physics=e.physics?j(e.physics):void 0,this.multiplayer=e.multiplayer?j(e.multiplayer):void 0,this.environment=e.environment?j(e.environment):void 0,this.viewport=e.viewport?j(e.viewport):void 0,this.connections=e.connections?j(e.connections):[]}toJSON(){return{format:1,type:`scene`,name:this.name,...this.dimension?{dimension:this.dimension}:{},...this.assets?{assets:j(this.assets)}:{},...this.constants?{constants:j(this.constants)}:{},...this.input?{input:j(this.input)}:{},...this.physics?{physics:j(this.physics)}:{},...this.multiplayer?{multiplayer:j(this.multiplayer)}:{},...this.environment?{environment:j(this.environment)}:{},...this.viewport?{viewport:j(this.viewport)}:{},root:yt(this.root),...this.connections.length>0?{connections:j(this.connections)}:{}}}};function St(e,t){if(typeof e!=`object`||!e)throw new y(`BAD_FORMAT`,`Scene JSON must be an object, got ${e===null?`null`:typeof e}.`);let n=e;wt(n);let r=Et(n.root,t,[],``,n.constants);Pt(r);let i=new mt;return t?.engine&&i._setEngine(t.engine),i.setRoot(r),jt(r,n.connections??[],t?.declareConnectionSignals),new xt(n,r,i)}function Ct(e,t){return Et(e,t,[],``,void 0)}function wt(e){if(e.format!==1)throw new y(`BAD_FORMAT`,`Unsupported scene format ${JSON.stringify(e.format)}; this engine reads format 1.`);if(e.type!==`scene`)throw new y(`BAD_FORMAT`,`Expected "type": "scene", got ${JSON.stringify(e.type)}.`);if(typeof e.name!=`string`||e.name===``)throw new y(`BAD_FORMAT`,`Scene "name" must be a non-empty string.`);if(e.dimension!==void 0&&e.dimension!==`2d`&&e.dimension!==`3d`)throw new y(`BAD_FORMAT`,`Scene "dimension" must be "2d" or "3d", got ${JSON.stringify(e.dimension)}.`);if(typeof e.root!=`object`||e.root===null)throw new y(`BAD_FORMAT`,`Scene "root" must be a node object.`);_t(e.viewport)}function Tt(e,t,n){return e instanceof y&&!e.details.path?new y(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 Et(e,t,n,r,i){let a=`${r}/${e.name}`;try{if(e.instance!==void 0&&e.type!==void 0)throw new y(`BAD_FORMAT`,`Node '${e.name}' declares both "type" and "instance" — they are mutually exclusive.`);if(e.instance!==void 0)return Dt(e,t,n,a,i);if(e.type===void 0)throw new y(`BAD_FORMAT`,`Node '${e.name}' must declare either "type" or "instance".`);let r=xe(e.type,pt(e.props,i));kt(r,e,t),r.constructor.validateJson?.(r);for(let o of e.children??[])r.addChild(Et(o,t,n,a,i));return r}catch(t){throw Tt(t,a,e)}}function Dt(e,t,n,r,i){let a=e.instance;if(!t?.resolveScene)throw new y(`UNRESOLVED_INSTANCE`,`Node '${e.name}' references instance '${a}' but no resolveScene option was provided.`);if(n.includes(a))throw new y(`UNRESOLVED_INSTANCE`,`Instance cycle detected: ${[...n,a].join(` → `)}.`);let o=t.resolveScene(a);if(!o)throw new y(`UNRESOLVED_INSTANCE`,`resolveScene returned nothing for instance '${a}' (node '${e.name}').`);wt(o);let s=pt(e.overrides??{},i),c=Et({...o.root,name:e.name,props:At(o.root.props??{},s)},t,[...n,a],Ot(r),o.constants);kt(c,{...e,type:void 0,props:void 0},t);for(let a of e.children??[])c.addChild(Et(a,t,n,r,i));return jt(c,o.connections??[],t?.declareConnectionSignals),c}function Ot(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function kt(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=j(t.tags)),t.script){e.script=j(t.script);let r=t.script.name;if(typeof r!=`string`||r===``)throw new y(`BAD_FORMAT`,`Node '${t.name}': "script" needs a non-empty "name" (a registered behavior).`);let i=n?.stubMissingBehaviors&&!we(r)?new class extends Se{}:Te(r,t.script.props);i.node=e,e.behavior=i;for(let t of _e(i.constructor))e.declareSignal(t)}t.network&&(e.network=j(t.network))}function At(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]=At(t,r):n[e]=r}return n}function jt(e,t,n=!1){for(let r of t){let t=Mt(e,r.from,r,`from`);(n||t.behavior instanceof Se)&&t.declareSignal(r.signal);let i=Mt(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 Se))throw new y(`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&&!Nt(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 y&&e.code===`UNKNOWN_SIGNAL`?new y(`UNKNOWN_SIGNAL`,`Connection from '${r.from}': ${e.message}`,e.details):e}}}function Mt(e,t,n,r){try{return e.getNode(t)}catch(e){throw e instanceof y?new y(`DANGLING_CONNECTION`,`Connection '${n.signal}' has a dangling '${r}' path '${t}': ${e.message}`):e}}function Nt(e,t){if(!(e instanceof Fe)||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 Pt(e){let t=new Map,n=e=>{if(e.uid!==null){let n=t.get(e.uid);if(n)throw new y(`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 Ft(){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 It=`attached`,Lt=1e3,Rt=1001,zt=1002,Bt=1003,Vt=1004,Ht=1005,Ut=1006,Wt=1007,Gt=1008,Kt=1009,qt=1010,Jt=1011,Yt=1012,Xt=1013,Zt=1014,Qt=1015,$t=1016,en=1017,tn=1018,nn=1020,rn=35902,an=35899,on=1021,sn=1022,cn=1023,ln=1026,un=1027,dn=1028,fn=1029,pn=1030,mn=1031,hn=1033,gn=33776,_n=33777,vn=33778,yn=33779,bn=35840,xn=35841,Sn=35842,Cn=35843,wn=36196,Tn=37492,En=37496,Dn=37488,On=37489,kn=37490,An=37491,jn=37808,Mn=37809,Nn=37810,Pn=37811,Fn=37812,In=37813,Ln=37814,Rn=37815,zn=37816,Bn=37817,Vn=37818,Hn=37819,Un=37820,Wn=37821,Gn=36492,Kn=36494,qn=36495,Jn=36283,Yn=36284,Xn=36285,Zn=36286,Qn=2200,$n=2201,er=2202,tr=2300,nr=2301,rr=2302,ir=2303,ar=2400,or=2401,sr=2402,cr=2500,lr=2501,ur=3200,dr=3201,fr=`srgb`,pr=`srgb-linear`,mr=`linear`,hr=`srgb`,gr=7680,_r=35044,vr=35048,yr=2e3;function br(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function xr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Sr(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function Cr(){let e=Sr(`canvas`);return e.style.display=`block`,e}var wr={},Tr=null;function Er(...e){let t=`THREE.`+e.shift();Tr?Tr(`log`,t,...e):console.log(t,...e)}function Dr(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 I(...e){e=Dr(e);let t=`THREE.`+e.shift();if(Tr)Tr(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function L(...e){e=Dr(e);let t=`THREE.`+e.shift();if(Tr)Tr(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Or(...e){let t=e.join(` `);t in wr||(wr[t]=!0,I(...e))}function kr(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 Ar={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},jr=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}}},Mr=`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(`.`),Nr=1234567,Pr=Math.PI/180,Fr=180/Math.PI;function Ir(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Mr[e&255]+Mr[e>>8&255]+Mr[e>>16&255]+Mr[e>>24&255]+`-`+Mr[t&255]+Mr[t>>8&255]+`-`+Mr[t>>16&15|64]+Mr[t>>24&255]+`-`+Mr[n&63|128]+Mr[n>>8&255]+`-`+Mr[n>>16&255]+Mr[n>>24&255]+Mr[r&255]+Mr[r>>8&255]+Mr[r>>16&255]+Mr[r>>24&255]).toLowerCase()}function R(e,t,n){return Math.max(t,Math.min(n,e))}function Lr(e,t){return(e%t+t)%t}function Rr(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function zr(e,t,n){return e===t?0:(n-e)/(t-e)}function Br(e,t,n){return(1-n)*e+n*t}function Vr(e,t,n,r){return Br(e,t,1-Math.exp(-n*r))}function Hr(e,t=1){return t-Math.abs(Lr(e,t*2)-t)}function Ur(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Wr(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Gr(e,t){return e+Math.floor(Math.random()*(t-e+1))}function Kr(e,t){return e+Math.random()*(t-e)}function qr(e){return e*(.5-Math.random())}function Jr(e){e!==void 0&&(Nr=e);let t=Nr+=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 Yr(e){return e*Pr}function Xr(e){return e*Fr}function Zr(e){return(e&e-1)==0&&e!==0}function Qr(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function $r(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ei(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:I(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function ti(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 ni(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 ri={DEG2RAD:Pr,RAD2DEG:Fr,generateUUID:Ir,clamp:R,euclideanModulo:Lr,mapLinear:Rr,inverseLerp:zr,lerp:Br,damp:Vr,pingpong:Hr,smoothstep:Ur,smootherstep:Wr,randInt:Gr,randFloat:Kr,randFloatSpread:qr,seededRandom:Jr,degToRad:Yr,radToDeg:Xr,isPowerOfTwo:Zr,ceilPowerOfTwo:Qr,floorPowerOfTwo:$r,setQuaternionFromProperEuler:ei,normalize:ni,denormalize:ti},z=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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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(R(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}},B=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:I(`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(R(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}},V=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(ai.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ai.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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this.z=R(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this.z=R(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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 ii.copy(this).projectOnVector(e),this.sub(ii)}reflect(e){return this.sub(ii.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(R(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}},ii=new V,ai=new B,H=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(oi.makeScale(e,t)),this}rotate(e){return this.premultiply(oi.makeRotation(-e)),this}translate(e,t){return this.premultiply(oi.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)}},oi=new H,si=new H().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ci=new H().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function li(){let e={enabled:!0,workingColorSpace:pr,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=di(e.r),e.g=di(e.g),e.b=di(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=fi(e.r),e.g=fi(e.g),e.b=fi(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===``?mr: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 Or(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Or(`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({[pr]:{primaries:t,whitePoint:r,transfer:mr,toXYZ:si,fromXYZ:ci,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:fr},outputColorSpaceConfig:{drawingBufferColorSpace:fr}},[fr]:{primaries:t,whitePoint:r,transfer:hr,toXYZ:si,fromXYZ:ci,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:fr}}}),e}var ui=li();function di(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function fi(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var pi,mi=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{pi===void 0&&(pi=Sr(`canvas`)),pi.width=e.width,pi.height=e.height;let t=pi.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=pi}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=Sr(`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]=di(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(di(t[e]/255)*255):t[e]=di(t[e]);return{data:t,width:e.width,height:e.height}}else return I(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},hi=0,gi=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:hi++}),this.uuid=Ir(),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(_i(r[t].image)):e.push(_i(r[t]))}else e=_i(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function _i(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?mi.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(I(`Texture: Unable to serialize Texture.`),{})}var vi=0,yi=new V,bi=class e extends jr{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=Rt,i=Rt,a=Ut,o=Gt,s=cn,c=Kt,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:vi++}),this.uuid=Ir(),this.name=``,this.source=new gi(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 z(0,0),this.repeat=new z(1,1),this.center=new z(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new H,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(yi).x}get height(){return this.source.getSize(yi).y}get depth(){return this.source.getSize(yi).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){I(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){I(`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 Lt:e.x-=Math.floor(e.x);break;case Rt:e.x=e.x<0?0:1;break;case zt: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 Lt:e.y-=Math.floor(e.y);break;case Rt:e.y=e.y<0?0:1;break;case zt: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++}};bi.DEFAULT_IMAGE=null,bi.DEFAULT_MAPPING=300,bi.DEFAULT_ANISOTROPY=1;var xi=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=R(this.x,e.x,t.x),this.y=R(this.y,e.y,t.y),this.z=R(this.z,e.z,t.z),this.w=R(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=R(this.x,e,t),this.y=R(this.y,e,t),this.z=R(this.z,e,t),this.w=R(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(R(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}},Si=class extends jr{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ut,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 xi(0,0,e,t),this.scissorTest=!1,this.viewport=new xi(0,0,e,t),this.textures=[];let r=new bi({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:Ut,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 gi(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`})}},Ci=class extends Si{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},wi=class extends bi{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=Bt,this.minFilter=Bt,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ti=class extends bi{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=Bt,this.minFilter=Bt,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},U=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/Ei.setFromMatrixColumn(e,0).length(),i=1/Ei.setFromMatrixColumn(e,1).length(),a=1/Ei.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(Oi,e,ki)}lookAt(e,t,n){let r=this.elements;return Mi.subVectors(e,t),Mi.lengthSq()===0&&(Mi.z=1),Mi.normalize(),Ai.crossVectors(n,Mi),Ai.lengthSq()===0&&(Math.abs(n.z)===1?Mi.x+=1e-4:Mi.z+=1e-4,Mi.normalize(),Ai.crossVectors(n,Mi)),Ai.normalize(),ji.crossVectors(Mi,Ai),r[0]=Ai.x,r[4]=ji.x,r[8]=Mi.x,r[1]=Ai.y,r[5]=ji.y,r[9]=Mi.y,r[2]=Ai.z,r[6]=ji.z,r[10]=Mi.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],ie=r[11],ae=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*ie,i[12]=a*w+o*O+s*te+c*ae,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*ie,i[13]=l*w+u*O+d*te+f*ae,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*ie,i[14]=p*w+m*O+h*te+g*ae,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*ie,i[15]=_*w+v*O+y*te+b*ae,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=Ei.set(r[0],r[1],r[2]).length(),o=Ei.set(r[4],r[5],r[6]).length(),s=Ei.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Di.copy(this);let c=1/a,l=1/o,u=1/s;return Di.elements[0]*=c,Di.elements[1]*=c,Di.elements[2]*=c,Di.elements[4]*=l,Di.elements[5]*=l,Di.elements[6]*=l,Di.elements[8]*=u,Di.elements[9]*=u,Di.elements[10]*=u,t.setFromRotationMatrix(Di),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=yr,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=yr,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}},Ei=new V,Di=new U,Oi=new V(0,0,0),ki=new V(1,1,1),Ai=new V,ji=new V,Mi=new V,Ni=new U,Pi=new B,Fi=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(R(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(-R(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(R(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(-R(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(R(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(-R(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:I(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Ni.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Ni,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Pi.setFromEuler(this),this.setFromQuaternion(Pi,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}};Fi.DEFAULT_ORDER=`XYZ`;var Ii=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}},Li=0,Ri=new V,zi=new B,Bi=new U,Vi=new V,Hi=new V,Ui=new V,Wi=new B,Gi=new V(1,0,0),Ki=new V(0,1,0),qi=new V(0,0,1),Ji={type:`added`},Yi={type:`removed`},Xi={type:`childadded`,child:null},Zi={type:`childremoved`,child:null},Qi=class e extends jr{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Li++}),this.uuid=Ir(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new V,n=new Fi,r=new B,i=new V(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 U},normalMatrix:{value:new H}}),this.matrix=new U,this.matrixWorld=new U,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ii,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 zi.setFromAxisAngle(e,t),this.quaternion.multiply(zi),this}rotateOnWorldAxis(e,t){return zi.setFromAxisAngle(e,t),this.quaternion.premultiply(zi),this}rotateX(e){return this.rotateOnAxis(Gi,e)}rotateY(e){return this.rotateOnAxis(Ki,e)}rotateZ(e){return this.rotateOnAxis(qi,e)}translateOnAxis(e,t){return Ri.copy(e).applyQuaternion(this.quaternion),this.position.add(Ri.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Gi,e)}translateY(e){return this.translateOnAxis(Ki,e)}translateZ(e){return this.translateOnAxis(qi,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Bi.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Vi.copy(e):Vi.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),Hi.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Bi.lookAt(Hi,Vi,this.up):Bi.lookAt(Vi,Hi,this.up),this.quaternion.setFromRotationMatrix(Bi),r&&(Bi.extractRotation(r.matrixWorld),zi.setFromRotationMatrix(Bi),this.quaternion.premultiply(zi.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(L(`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(Ji),Xi.child=e,this.dispatchEvent(Xi),Xi.child=null):L(`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(Yi),Zi.child=e,this.dispatchEvent(Zi),Zi.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),Bi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Bi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Bi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Ji),Xi.child=e,this.dispatchEvent(Xi),Xi.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(Hi,e,Ui),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Hi,Wi,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}};Qi.DEFAULT_UP=new V(0,1,0),Qi.DEFAULT_MATRIX_AUTO_UPDATE=!0,Qi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var $i=class extends Qi{constructor(){super(),this.isGroup=!0,this.type=`Group`}},ea={type:`move`},ta=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new $i,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 $i,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new V,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new V),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new $i,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new V,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new V,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(ea)))}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 $i;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},na={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},ra={h:0,s:0,l:0},ia={h:0,s:0,l:0};function aa(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 W=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=fr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ui.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=ui.workingColorSpace){return this.r=e,this.g=t,this.b=n,ui.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=ui.workingColorSpace){if(e=Lr(e,1),t=R(t,0,1),n=R(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=aa(i,r,e+1/3),this.g=aa(i,r,e),this.b=aa(i,r,e-1/3)}return ui.colorSpaceToWorking(this,r),this}setStyle(e,t=fr){function n(t){t!==void 0&&parseFloat(t)<1&&I(`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:I(`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);I(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=fr){let n=na[e.toLowerCase()];return n===void 0?I(`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=di(e.r),this.g=di(e.g),this.b=di(e.b),this}copyLinearToSRGB(e){return this.r=fi(e.r),this.g=fi(e.g),this.b=fi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=fr){return ui.workingToColorSpace(oa.copy(this),e),Math.round(R(oa.r*255,0,255))*65536+Math.round(R(oa.g*255,0,255))*256+Math.round(R(oa.b*255,0,255))}getHexString(e=fr){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ui.workingColorSpace){ui.workingToColorSpace(oa.copy(this),t);let n=oa.r,r=oa.g,i=oa.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=ui.workingColorSpace){return ui.workingToColorSpace(oa.copy(this),t),e.r=oa.r,e.g=oa.g,e.b=oa.b,e}getStyle(e=fr){ui.workingToColorSpace(oa.copy(this),e);let t=oa.r,n=oa.g,r=oa.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(ra),this.setHSL(ra.h+e,ra.s+t,ra.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(ra),e.getHSL(ia);let n=Br(ra.h,ia.h,t),r=Br(ra.s,ia.s,t),i=Br(ra.l,ia.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}},oa=new W;W.NAMES=na;var sa=class e{constructor(e,t=1,n=1e3){this.isFog=!0,this.name=``,this.color=new W(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}}},ca=class extends Qi{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 Fi,this.environmentIntensity=1,this.environmentRotation=new Fi,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}},la=new V,ua=new V,da=new V,fa=new V,pa=new V,ma=new V,ha=new V,ga=new V,_a=new V,va=new V,ya=new xi,ba=new xi,xa=new xi,Sa=class e{constructor(e=new V,t=new V,n=new V){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),la.subVectors(e,t),r.cross(la);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){la.subVectors(r,t),ua.subVectors(n,t),da.subVectors(e,t);let a=la.dot(la),o=la.dot(ua),s=la.dot(da),c=ua.dot(ua),l=ua.dot(da),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,fa)===null?!1:fa.x>=0&&fa.y>=0&&fa.x+fa.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,fa)===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,fa.x),s.addScaledVector(a,fa.y),s.addScaledVector(o,fa.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return ya.setScalar(0),ba.setScalar(0),xa.setScalar(0),ya.fromBufferAttribute(e,t),ba.fromBufferAttribute(e,n),xa.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(ya,i.x),a.addScaledVector(ba,i.y),a.addScaledVector(xa,i.z),a}static isFrontFacing(e,t,n,r){return la.subVectors(n,t),ua.subVectors(e,t),la.cross(ua).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 la.subVectors(this.c,this.b),ua.subVectors(this.a,this.b),la.cross(ua).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;pa.subVectors(r,n),ma.subVectors(i,n),ga.subVectors(e,n);let s=pa.dot(ga),c=ma.dot(ga);if(s<=0&&c<=0)return t.copy(n);_a.subVectors(e,r);let l=pa.dot(_a),u=ma.dot(_a);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(pa,a);va.subVectors(e,i);let f=pa.dot(va),p=ma.dot(va);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(ma,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return ha.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(ha,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(pa,a).addScaledVector(ma,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Ca=class{constructor(e=new V(1/0,1/0,1/0),t=new V(-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(Ta.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ta.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=Ta.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,Ta):Ta.fromBufferAttribute(r,t),Ta.applyMatrix4(e.matrixWorld),this.expandByPoint(Ta);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Ea.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Ea.copy(e.boundingBox)),Ea.applyMatrix4(e.matrixWorld),this.union(Ea)}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,Ta),Ta.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(Na),Pa.subVectors(this.max,Na),Da.subVectors(e.a,Na),Oa.subVectors(e.b,Na),ka.subVectors(e.c,Na),Aa.subVectors(Oa,Da),ja.subVectors(ka,Oa),Ma.subVectors(Da,ka);let t=[0,-Aa.z,Aa.y,0,-ja.z,ja.y,0,-Ma.z,Ma.y,Aa.z,0,-Aa.x,ja.z,0,-ja.x,Ma.z,0,-Ma.x,-Aa.y,Aa.x,0,-ja.y,ja.x,0,-Ma.y,Ma.x,0];return!La(t,Da,Oa,ka,Pa)||(t=[1,0,0,0,1,0,0,0,1],!La(t,Da,Oa,ka,Pa))?!1:(Fa.crossVectors(Aa,ja),t=[Fa.x,Fa.y,Fa.z],La(t,Da,Oa,ka,Pa))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ta).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ta).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:(wa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wa),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}},wa=[new V,new V,new V,new V,new V,new V,new V,new V],Ta=new V,Ea=new Ca,Da=new V,Oa=new V,ka=new V,Aa=new V,ja=new V,Ma=new V,Na=new V,Pa=new V,Fa=new V,Ia=new V;function La(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ia.fromArray(e,a);let o=i.x*Math.abs(Ia.x)+i.y*Math.abs(Ia.y)+i.z*Math.abs(Ia.z),s=t.dot(Ia),c=n.dot(Ia),l=r.dot(Ia);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Ra=za();function za(){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 Ba(e){Math.abs(e)>65504&&I(`DataUtils.toHalfFloat(): Value out of range.`),e=R(e,-65504,65504),Ra.floatView[0]=e;let t=Ra.uint32View[0],n=t>>23&511;return Ra.baseTable[n]+((t&8388607)>>Ra.shiftTable[n])}function Va(e){let t=e>>10;return Ra.uint32View[0]=Ra.mantissaTable[Ra.offsetTable[t]+(e&1023)]+Ra.exponentTable[t],Ra.floatView[0]}var Ha=class{static toHalfFloat(e){return Ba(e)}static fromHalfFloat(e){return Va(e)}},Ua=new V,Wa=new z,Ga=0,G=class extends jr{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:Ga++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=_r,this.updateRanges=[],this.gpuType=Qt,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++)Wa.fromBufferAttribute(this,t),Wa.applyMatrix3(e),this.setXY(t,Wa.x,Wa.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyMatrix3(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyMatrix4(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.applyNormalMatrix(e),this.setXYZ(t,Ua.x,Ua.y,Ua.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ua.fromBufferAttribute(this,t),Ua.transformDirection(e),this.setXYZ(t,Ua.x,Ua.y,Ua.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=ti(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ni(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ti(t,this.array)),t}setX(e,t){return this.normalized&&(t=ni(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ti(t,this.array)),t}setY(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}setW(e,t){return this.normalized&&(t=ni(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ni(t,this.array),n=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(r,this.array),i=ni(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`})}},Ka=class extends G{constructor(e,t,n){super(new Uint16Array(e),t,n)}},qa=class extends G{constructor(e,t,n){super(new Uint32Array(e),t,n)}},Ja=class extends G{constructor(e,t,n){super(new Float32Array(e),t,n)}},Ya=new Ca,Xa=new V,Za=new V,Qa=class{constructor(e=new V,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?Ya.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;Xa.subVectors(e,this.center);let t=Xa.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Xa,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):(Za.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Xa.copy(e.center).add(Za)),this.expandByPoint(Xa.copy(e.center).sub(Za))),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}},$a=0,eo=new U,to=new Qi,no=new V,ro=new Ca,io=new Ca,ao=new V,K=class e extends jr{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:$a++}),this.uuid=Ir(),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(br(e)?qa:Ka)(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 H().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 eo.makeRotationFromQuaternion(e),this.applyMatrix4(eo),this}rotateX(e){return eo.makeRotationX(e),this.applyMatrix4(eo),this}rotateY(e){return eo.makeRotationY(e),this.applyMatrix4(eo),this}rotateZ(e){return eo.makeRotationZ(e),this.applyMatrix4(eo),this}translate(e,t,n){return eo.makeTranslation(e,t,n),this.applyMatrix4(eo),this}scale(e,t,n){return eo.makeScale(e,t,n),this.applyMatrix4(eo),this}lookAt(e){return to.lookAt(e),to.updateMatrix(),this.applyMatrix4(to.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(no).negate(),this.translate(no.x,no.y,no.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 Ja(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&&I(`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 Ca);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){L(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new V(-1/0,-1/0,-1/0),new V(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];ro.setFromBufferAttribute(n),this.morphTargetsRelative?(ao.addVectors(this.boundingBox.min,ro.min),this.boundingBox.expandByPoint(ao),ao.addVectors(this.boundingBox.max,ro.max),this.boundingBox.expandByPoint(ao)):(this.boundingBox.expandByPoint(ro.min),this.boundingBox.expandByPoint(ro.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&L(`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 Qa);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){L(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new V,1/0);return}if(e){let n=this.boundingSphere.center;if(ro.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];io.setFromBufferAttribute(n),this.morphTargetsRelative?(ao.addVectors(ro.min,io.min),ro.expandByPoint(ao),ao.addVectors(ro.max,io.max),ro.expandByPoint(ao)):(ro.expandByPoint(io.min),ro.expandByPoint(io.max))}ro.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)ao.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(ao));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++)ao.fromBufferAttribute(a,t),o&&(no.fromBufferAttribute(e,t),ao.add(no)),r=Math.max(r,n.distanceToSquared(ao))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&L(`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){L(`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 G(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new V,s[e]=new V;let c=new V,l=new V,u=new V,d=new z,f=new z,p=new z,m=new V,h=new V;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 V,y=new V,b=new V,x=new V;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 G(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 V,i=new V,a=new V,o=new V,s=new V,c=new V,l=new V,u=new V;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++)ao.fromBufferAttribute(e,t),ao.normalize(),e.setXYZ(t,ao.x,ao.y,ao.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 G(a,r,i)}if(this.index===null)return I(`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`})}},oo=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=_r,this.updateRanges=[],this.version=0,this.uuid=Ir()}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=Ir()),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=Ir()),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}}},so=new V,co=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++)so.fromBufferAttribute(this,t),so.applyMatrix4(e),this.setXYZ(t,so.x,so.y,so.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)so.fromBufferAttribute(this,t),so.applyNormalMatrix(e),this.setXYZ(t,so.x,so.y,so.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)so.fromBufferAttribute(this,t),so.transformDirection(e),this.setXYZ(t,so.x,so.y,so.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=ti(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ni(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ni(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ni(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=ti(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=ti(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=ti(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=ti(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ni(t,this.array),n=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(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=ni(t,this.array),n=ni(n,this.array),r=ni(r,this.array),i=ni(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){Er(`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 G(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){Er(`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}}},lo=0,uo=class extends jr{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:lo++}),this.uuid=Ir(),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 W(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=gr,this.stencilZFail=gr,this.stencilZPass=gr,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){I(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){I(`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++}},fo=new V,po=new V,mo=new V,ho=new V,go=new V,_o=new V,vo=new V,yo=class{constructor(e=new V,t=new V(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,fo)),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=fo.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(fo.copy(this.origin).addScaledVector(this.direction,t),fo.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){po.copy(e).add(t).multiplyScalar(.5),mo.copy(t).sub(e).normalize(),ho.copy(this.origin).sub(po);let i=e.distanceTo(t)*.5,a=-this.direction.dot(mo),o=ho.dot(this.direction),s=-ho.dot(mo),c=ho.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(po).addScaledVector(mo,d),f}intersectSphere(e,t){fo.subVectors(e.center,this.origin);let n=fo.dot(this.direction),r=fo.dot(fo)-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,fo)!==null}intersectTriangle(e,t,n,r,i){go.subVectors(t,e),_o.subVectors(n,e),vo.crossVectors(go,_o);let a=this.direction.dot(vo),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;ho.subVectors(this.origin,e);let s=o*this.direction.dot(_o.crossVectors(ho,_o));if(s<0)return null;let c=o*this.direction.dot(go.cross(ho));if(c<0||s+c>a)return null;let l=-o*ho.dot(vo);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)}},bo=class extends uo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new W(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 Fi,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}},xo=new U,So=new yo,Co=new Qa,wo=new V,To=new V,Eo=new V,Do=new V,Oo=new V,ko=new V,Ao=new V,jo=new V,Mo=class extends Qi{constructor(e=new K,t=new bo){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){ko.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Oo.fromBufferAttribute(s,e),a?ko.addScaledVector(Oo,r):ko.addScaledVector(Oo.sub(t),r))}t.add(ko)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Co.copy(n.boundingSphere),Co.applyMatrix4(i),So.copy(e.ray).recast(e.near),!(Co.containsPoint(So.origin)===!1&&(So.intersectSphere(Co,wo)===null||So.origin.distanceToSquared(wo)>(e.far-e.near)**2))&&(xo.copy(i).invert(),So.copy(e.ray).applyMatrix4(xo),!(n.boundingBox!==null&&So.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,So)))}_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=Po(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=Po(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=Po(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=Po(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function No(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;jo.copy(s),jo.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(jo);return l<n.near||l>n.far?null:{distance:l,point:jo.clone(),object:e}}function Po(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,To),e.getVertexPosition(c,Eo),e.getVertexPosition(l,Do);let u=No(e,t,n,r,To,Eo,Do,Ao);if(u){let e=new V;Sa.getBarycoord(Ao,To,Eo,Do,e),i&&(u.uv=Sa.getInterpolatedAttribute(i,s,c,l,e,new z)),a&&(u.uv1=Sa.getInterpolatedAttribute(a,s,c,l,e,new z)),o&&(u.normal=Sa.getInterpolatedAttribute(o,s,c,l,e,new V),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new V,materialIndex:0};Sa.getNormal(To,Eo,Do,t.normal),u.face=t,u.barycoord=e}return u}var Fo=new xi,Io=new xi,Lo=new xi,Ro=new xi,zo=new U,Bo=new V,Vo=new Qa,Ho=new U,Uo=new yo,Wo=class extends Mo{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=It,this.bindMatrix=new U,this.bindMatrixInverse=new U,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ca),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Bo),this.boundingBox.expandByPoint(Bo)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Qa),this.boundingSphere.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Bo),this.boundingSphere.expandByPoint(Bo)}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(),Vo.copy(this.boundingSphere),Vo.applyMatrix4(r),e.ray.intersectsSphere(Vo)!==!1&&(Ho.copy(r).invert(),Uo.copy(e.ray).applyMatrix4(Ho),!(this.boundingBox!==null&&Uo.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,Uo)))}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 xi,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():I(`SkinnedMesh: Unrecognized bindMode: `+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;Io.fromBufferAttribute(r.attributes.skinIndex,e),Lo.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?(Fo.copy(t),t.set(0,0,0,0)):(Fo.set(...t,1),t.set(0,0,0)),Fo.applyMatrix4(this.bindMatrix);for(let e=0;e<4;e++){let r=Lo.getComponent(e);if(r!==0){let i=Io.getComponent(e);zo.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(Ro.copy(Fo).applyMatrix4(zo),r)}}return t.isVector4&&(t.w=Fo.w),t.applyMatrix4(this.bindMatrixInverse)}},Go=class extends Qi{constructor(){super(),this.isBone=!0,this.type=`Bone`}},Ko=class extends bi{constructor(e=null,t=1,n=1,r,i,a,o,s,c=Bt,l=Bt,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}},qo=new U,Jo=new U,Yo=class e{constructor(e=[],t=[]){this.uuid=Ir(),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){I(`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 U)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let t=new U;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:Jo;qo.multiplyMatrices(i,t[r]),qo.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 Ko(t,e,e,cn,Qt);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&&(I(`Skeleton: No bone found with UUID:`,r),i=new Go),this.bones.push(i),this.boneInverses.push(new U().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}},Xo=class extends G{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}},Zo=new U,Qo=new U,$o=[],es=new Ca,ts=new U,ns=new Mo,rs=new Qa,is=class extends Mo{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Xo(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,ts)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Ca),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zo),es.copy(e.boundingBox).applyMatrix4(Zo),this.boundingBox.union(es)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Qa),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Zo),rs.copy(e.boundingSphere).applyMatrix4(Zo),this.boundingSphere.union(rs)}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(ns.geometry=this.geometry,ns.material=this.material,ns.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),rs.copy(this.boundingSphere),rs.applyMatrix4(n),e.ray.intersectsSphere(rs)!==!1))for(let i=0;i<r;i++){this.getMatrixAt(i,Zo),Qo.multiplyMatrices(n,Zo),ns.matrixWorld=Qo,ns.raycast(e,$o);for(let e=0,n=$o.length;e<n;e++){let n=$o[e];n.instanceId=i,n.object=this,t.push(n)}$o.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new Xo(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 Ko(new Float32Array(r*this.count),r,this.count,dn,Qt));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)}},as=new V,os=new V,ss=new H,cs=class{constructor(e=new V(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=as.subVectors(n,t).cross(os.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(as),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||ss.getNormalMatrix(e),r=this.coplanarPoint(as).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)}},ls=new Qa,us=new z(.5,.5),ds=new V,fs=class{constructor(e=new cs,t=new cs,n=new cs,r=new cs,i=new cs,a=new cs){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=yr,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(),ls.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ls.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ls)}intersectsSprite(e){return ls.center.set(0,0,0),ls.radius=.7071067811865476+us.distanceTo(e.center),ls.applyMatrix4(e.matrixWorld),this.intersectsSphere(ls)}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(ds.x=r.normal.x>0?e.max.x:e.min.x,ds.y=r.normal.y>0?e.max.y:e.min.y,ds.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(ds)<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)}},ps=class extends uo{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new W(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}},ms=new V,hs=new V,gs=new U,_s=new yo,vs=new Qa,ys=new V,bs=new V,xs=class extends Qi{constructor(e=new K,t=new ps){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++)ms.fromBufferAttribute(t,e-1),hs.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=ms.distanceTo(hs);e.setAttribute(`lineDistance`,new Ja(n,1))}else I(`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(),vs.copy(n.boundingSphere),vs.applyMatrix4(r),vs.radius+=i,e.ray.intersectsSphere(vs)===!1)return;gs.copy(r).invert(),_s.copy(e.ray).applyMatrix4(gs);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=Ss(this,e,_s,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=Ss(this,e,_s,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=Ss(this,e,_s,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=Ss(this,e,_s,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 Ss(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(ms.fromBufferAttribute(s,i),hs.fromBufferAttribute(s,a),n.distanceSqToSegment(ms,hs,ys,bs)>r)return;ys.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(ys);if(!(c<t.near||c>t.far))return{distance:c,point:bs.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Cs=new V,ws=new V,Ts=class extends xs{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)Cs.fromBufferAttribute(t,e),ws.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+Cs.distanceTo(ws);e.setAttribute(`lineDistance`,new Ja(n,1))}else I(`LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Es=class extends xs{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type=`LineLoop`}},Ds=class extends uo{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new W(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}},Os=new U,ks=new yo,As=new Qa,js=new V,Ms=class extends Qi{constructor(e=new K,t=new Ds){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(),As.copy(n.boundingSphere),As.applyMatrix4(r),As.radius+=i,e.ray.intersectsSphere(As)===!1)return;Os.copy(r).invert(),ks.copy(e.ray).applyMatrix4(Os);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);js.fromBufferAttribute(l,n),Ns(js,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++)js.fromBufferAttribute(l,a),Ns(js,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 Ns(e,t,n,r,i,a,o){let s=ks.distanceSqToPoint(e);if(s<n){let n=new V;ks.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 Ps=class extends bi{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}},Fs=class extends bi{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}},Is=class extends bi{constructor(e,t,n=Zt,r,i,a,o=Bt,s=Bt,c,l=ln,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 gi(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}},Ls=class extends Is{constructor(e,t=Zt,n=301,r,i,a=Bt,o=Bt,s,c=ln){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}},Rs=class extends bi{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},zs=class e extends K{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 Ja(c,3)),this.setAttribute(`normal`,new Ja(l,3)),this.setAttribute(`uv`,new Ja(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 V;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)}},Bs=class e extends K{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 V,g=new V;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 Ja(o,3)),this.setAttribute(`normal`,new Ja(s,3)),this.setAttribute(`uv`,new Ja(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)}},Vs=class e extends K{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 Ja(u,3)),this.setAttribute(`normal`,new Ja(d,3)),this.setAttribute(`uv`,new Ja(f,2));function _(){let a=new V,_=new V,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 z,m=new V,_=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)}},Hs=class e extends Vs{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)}},Us=class e extends K{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 Ja(i,3)),this.setAttribute(`normal`,new Ja(i.slice(),3)),this.setAttribute(`uv`,new Ja(a,2)),r===0?this.computeVertexNormals():this.normalizeNormals();function o(e){let n=new V,r=new V,i=new V;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 V;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 V;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 V,t=new V,n=new V,r=new V,o=new z,s=new z,c=new z;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)}},Ws=class e extends Us{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)}},Gs=class e extends K{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 Ja(p,3)),this.setAttribute(`normal`,new Ja(m,3)),this.setAttribute(`uv`,new Ja(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)}},Ks=class e extends K{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 V,d=new V,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 Ja(p,3)),this.setAttribute(`normal`,new Ja(m,3)),this.setAttribute(`uv`,new Ja(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 qs(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(Ys(i))i.isRenderTargetTexture?(I(`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(Ys(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 Js(e){let t={};for(let n=0;n<e.length;n++){let r=qs(e[n]);for(let e in r)t[e]=r[e]}return t}function Ys(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function Xs(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Zs(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:ui.workingColorSpace}var Qs={clone:qs,merge:Js},$s=`void main() {
2
2
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3
3
  }`,ec=`void main() {
4
4
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
@@ -4050,7 +4050,7 @@ Material Type: `+t.type+`
4050
4050
 
4051
4051
  Program Info Log: `+o+`
4052
4052
  `+e+`
4053
- `+n)}else o===``?(s===``||c===``)&&(u=!1):I(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new kd(i,h),T=Wd(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,jd)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Md++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var pf=0,mf=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new hf(e),t.set(e,n)),n}},hf=class{constructor(e){this.id=pf++,this.code=e,this.usedTimes=0}};function gf(e){return e===1030||e===37490||e===36285}function _f(e,t,n,r,i,a){let o=new Ii,s=new mf,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&I(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,ee,k;if(C){let e=Rl[C];D=e.vertexShader,O=e.fragmentShader}else D=i.vertexShader,O=i.fragmentShader,s.update(i),ee=s.getVertexShaderID(i),k=s.getFragmentShaderID(i);let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),re=h.isInstancedMesh===!0,ie=h.isBatchedMesh===!0,ae=!!i.map,oe=!!i.matcap,se=!!x,ce=!!i.aoMap,le=!!i.lightMap,ue=!!i.bumpMap,de=!!i.normalMap,fe=!!i.displacementMap,A=!!i.emissiveMap,pe=!!i.metalnessMap,me=!!i.roughnessMap,j=i.anisotropy>0,he=i.clearcoat>0,ge=i.dispersion>0,_e=i.iridescence>0,ve=i.sheen>0,ye=i.transmission>0,be=j&&!!i.anisotropyMap,xe=he&&!!i.clearcoatMap,Se=he&&!!i.clearcoatNormalMap,M=he&&!!i.clearcoatRoughnessMap,Ce=_e&&!!i.iridescenceMap,we=_e&&!!i.iridescenceThicknessMap,Te=ve&&!!i.sheenColorMap,N=ve&&!!i.sheenRoughnessMap,Ee=!!i.specularMap,P=!!i.specularColorMap,F=!!i.specularIntensityMap,De=ye&&!!i.transmissionMap,Oe=ye&&!!i.thicknessMap,ke=!!i.gradientMap,Ae=!!i.alphaMap,je=i.alphaTest>0,Me=!!i.alphaHash,Ne=!!i.extensions,Pe=0;i.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Pe=e.toneMapping);let Fe={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:ee,customFragmentShaderID:k,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:ie,batchingColor:ie&&h._colorsTexture!==null,instancing:re,instancingColor:re&&h.instanceColor!==null,instancingMorph:re&&h.morphTexture!==null,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:ui.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ae,matcap:oe,envMap:se,envMapMode:se&&x.mapping,envMapCubeUVHeight:S,aoMap:ce,lightMap:le,bumpMap:ue,normalMap:de,displacementMap:fe,emissiveMap:A,normalMapObjectSpace:de&&i.normalMapType===1,normalMapTangentSpace:de&&i.normalMapType===0,packedNormalMap:de&&i.normalMapType===0&&gf(i.normalMap.format),metalnessMap:pe,roughnessMap:me,anisotropy:j,anisotropyMap:be,clearcoat:he,clearcoatMap:xe,clearcoatNormalMap:Se,clearcoatRoughnessMap:M,dispersion:ge,iridescence:_e,iridescenceMap:Ce,iridescenceThicknessMap:we,sheen:ve,sheenColorMap:Te,sheenRoughnessMap:N,specularMap:Ee,specularColorMap:P,specularIntensityMap:F,transmission:ye,transmissionMap:De,thicknessMap:Oe,gradientMap:ke,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Ae,alphaTest:je,alphaHash:Me,combine:i.combine,mapUv:ae&&m(i.map.channel),aoMapUv:ce&&m(i.aoMap.channel),lightMapUv:le&&m(i.lightMap.channel),bumpMapUv:ue&&m(i.bumpMap.channel),normalMapUv:de&&m(i.normalMap.channel),displacementMapUv:fe&&m(i.displacementMap.channel),emissiveMapUv:A&&m(i.emissiveMap.channel),metalnessMapUv:pe&&m(i.metalnessMap.channel),roughnessMapUv:me&&m(i.roughnessMap.channel),anisotropyMapUv:be&&m(i.anisotropyMap.channel),clearcoatMapUv:xe&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:Se&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:M&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:we&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:Te&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:N&&m(i.sheenRoughnessMap.channel),specularMapUv:Ee&&m(i.specularMap.channel),specularColorMapUv:P&&m(i.specularColorMap.channel),specularIntensityMapUv:F&&m(i.specularIntensityMap.channel),transmissionMapUv:De&&m(i.transmissionMap.channel),thicknessMapUv:Oe&&m(i.thicknessMap.channel),alphaMapUv:Ae&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(de||j),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ae||Ae),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&de===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:h.isSkinnedMesh===!0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ae&&i.map.isVideoTexture===!0&&ui.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:A&&i.emissiveMap.isVideoTexture===!0&&ui.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Ne&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ne&&i.extensions.multiDraw===!0||ie)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Fe.vertexUv1s=c.has(1),Fe.vertexUv2s=c.has(2),Fe.vertexUv3s=c.has(3),c.clear(),Fe}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Rl[t];n=Qs.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new ff(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function vf(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function yf(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function bf(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function xf(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||yf),r.length>1&&r.sort(t||bf),i.length>1&&i.sort(t||bf)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function Sf(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new xf,e.set(t,[i])):n>=r.length?(i=new xf,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Cf(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new V,color:new W};break;case`SpotLight`:n={position:new V,direction:new V,color:new W,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new V,color:new W,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new V,skyColor:new W,groundColor:new W};break;case`RectAreaLight`:n={color:new W,position:new V,halfWidth:new V,halfHeight:new V};break}return e[t.id]=n,n}}}function wf(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Tf=0;function Ef(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Df(e){let t=new Cf,n=wf(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new V);let i=new V,a=new U,o=new U;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(Ef);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=null;if(y.shadow&&y.shadow.map&&(C=y.shadow.map.texture.format===1030?y.shadow.map.texture:y.shadow.map.depthTexture||y.shadow.map.texture),y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=J.LTC_FLOAT_1,r.rectAreaLTC2=J.LTC_FLOAT_2):(r.rectAreaLTC1=J.LTC_HALF_1,r.rectAreaLTC2=J.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Tf++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function Of(e){let t=new Df(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function kf(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new Of(e),t.set(n,[a])):r>=i.length?(a=new Of(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var Af=`void main() {
4053
+ `+n)}else o===``?(s===``||c===``)&&(u=!1):I(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new kd(i,h),T=Wd(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,jd)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Md++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var pf=0,mf=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new hf(e),t.set(e,n)),n}},hf=class{constructor(e){this.id=pf++,this.code=e,this.usedTimes=0}};function gf(e){return e===1030||e===37490||e===36285}function _f(e,t,n,r,i,a){let o=new Ii,s=new mf,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&I(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,A;if(C){let e=Rl[C];D=e.vertexShader,O=e.fragmentShader}else D=i.vertexShader,O=i.fragmentShader,s.update(i),k=s.getVertexShaderID(i),A=s.getFragmentShaderID(i);let ee=e.getRenderTarget(),te=e.state.buffers.depth.getReversed(),ne=h.isInstancedMesh===!0,re=h.isBatchedMesh===!0,ie=!!i.map,ae=!!i.matcap,oe=!!x,se=!!i.aoMap,ce=!!i.lightMap,le=!!i.bumpMap,ue=!!i.normalMap,de=!!i.displacementMap,j=!!i.emissiveMap,fe=!!i.metalnessMap,pe=!!i.roughnessMap,M=i.anisotropy>0,me=i.clearcoat>0,he=i.dispersion>0,ge=i.iridescence>0,_e=i.sheen>0,ve=i.transmission>0,ye=M&&!!i.anisotropyMap,be=me&&!!i.clearcoatMap,xe=me&&!!i.clearcoatNormalMap,N=me&&!!i.clearcoatRoughnessMap,Se=ge&&!!i.iridescenceMap,Ce=ge&&!!i.iridescenceThicknessMap,we=_e&&!!i.sheenColorMap,P=_e&&!!i.sheenRoughnessMap,Te=!!i.specularMap,F=!!i.specularColorMap,Ee=!!i.specularIntensityMap,De=ve&&!!i.transmissionMap,Oe=ve&&!!i.thicknessMap,ke=!!i.gradientMap,Ae=!!i.alphaMap,je=i.alphaTest>0,Me=!!i.alphaHash,Ne=!!i.extensions,Pe=0;i.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(Pe=e.toneMapping);let Fe={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:A,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:re,batchingColor:re&&h._colorsTexture!==null,instancing:ne,instancingColor:ne&&h.instanceColor!==null,instancingMorph:ne&&h.morphTexture!==null,outputColorSpace:ee===null?e.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:ui.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ie,matcap:ae,envMap:oe,envMapMode:oe&&x.mapping,envMapCubeUVHeight:S,aoMap:se,lightMap:ce,bumpMap:le,normalMap:ue,displacementMap:de,emissiveMap:j,normalMapObjectSpace:ue&&i.normalMapType===1,normalMapTangentSpace:ue&&i.normalMapType===0,packedNormalMap:ue&&i.normalMapType===0&&gf(i.normalMap.format),metalnessMap:fe,roughnessMap:pe,anisotropy:M,anisotropyMap:ye,clearcoat:me,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:N,dispersion:he,iridescence:ge,iridescenceMap:Se,iridescenceThicknessMap:Ce,sheen:_e,sheenColorMap:we,sheenRoughnessMap:P,specularMap:Te,specularColorMap:F,specularIntensityMap:Ee,transmission:ve,transmissionMap:De,thicknessMap:Oe,gradientMap:ke,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Ae,alphaTest:je,alphaHash:Me,combine:i.combine,mapUv:ie&&m(i.map.channel),aoMapUv:se&&m(i.aoMap.channel),lightMapUv:ce&&m(i.lightMap.channel),bumpMapUv:le&&m(i.bumpMap.channel),normalMapUv:ue&&m(i.normalMap.channel),displacementMapUv:de&&m(i.displacementMap.channel),emissiveMapUv:j&&m(i.emissiveMap.channel),metalnessMapUv:fe&&m(i.metalnessMap.channel),roughnessMapUv:pe&&m(i.roughnessMap.channel),anisotropyMapUv:ye&&m(i.anisotropyMap.channel),clearcoatMapUv:be&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:xe&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:N&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:Se&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:Ce&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:we&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:P&&m(i.sheenRoughnessMap.channel),specularMapUv:Te&&m(i.specularMap.channel),specularColorMapUv:F&&m(i.specularColorMap.channel),specularIntensityMapUv:Ee&&m(i.specularIntensityMap.channel),transmissionMapUv:De&&m(i.transmissionMap.channel),thicknessMapUv:Oe&&m(i.thicknessMap.channel),alphaMapUv:Ae&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(ue||M),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ie||Ae),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&ue===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:te,skinning:h.isSkinnedMesh===!0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ie&&i.map.isVideoTexture===!0&&ui.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:j&&i.emissiveMap.isVideoTexture===!0&&ui.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Ne&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ne&&i.extensions.multiDraw===!0||re)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Fe.vertexUv1s=c.has(1),Fe.vertexUv2s=c.has(2),Fe.vertexUv3s=c.has(3),c.clear(),Fe}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Rl[t];n=Qs.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new ff(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function vf(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function yf(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function bf(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function xf(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||yf),r.length>1&&r.sort(t||bf),i.length>1&&i.sort(t||bf)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function Sf(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new xf,e.set(t,[i])):n>=r.length?(i=new xf,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Cf(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new V,color:new W};break;case`SpotLight`:n={position:new V,direction:new V,color:new W,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new V,color:new W,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new V,skyColor:new W,groundColor:new W};break;case`RectAreaLight`:n={color:new W,position:new V,halfWidth:new V,halfHeight:new V};break}return e[t.id]=n,n}}}function wf(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new z,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Tf=0;function Ef(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Df(e){let t=new Cf,n=wf(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new V);let i=new V,a=new U,o=new U;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(Ef);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=null;if(y.shadow&&y.shadow.map&&(C=y.shadow.map.texture.format===1030?y.shadow.map.texture:y.shadow.map.depthTexture||y.shadow.map.texture),y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=J.LTC_FLOAT_1,r.rectAreaLTC2=J.LTC_FLOAT_2):(r.rectAreaLTC1=J.LTC_HALF_1,r.rectAreaLTC2=J.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Tf++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function Of(e){let t=new Df(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function kf(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new Of(e),t.set(n,[a])):r>=i.length?(a=new Of(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var Af=`void main() {
4054
4054
  gl_Position = vec4( position, 1.0 );
4055
4055
  }`,jf=`uniform sampler2D shadow_pass;
4056
4056
  uniform vec2 resolution;
@@ -4077,7 +4077,7 @@ void main() {
4077
4077
  squared_mean = squared_mean / samples;
4078
4078
  float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
4079
4079
  gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
4080
- }`,Mf=[new V(1,0,0),new V(-1,0,0),new V(0,1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1)],Nf=[new V(0,-1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1),new V(0,-1,0),new V(0,-1,0)],Pf=new U,Ff=new V,If=new V;function Lf(e,t,n){let r=new fs,i=new z,a=new z,o=new xi,s=new ac,c=new oc,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new tc({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new z},radius:{value:4}},vertexShader:Af,fragmentShader:jf}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new K;m.setAttribute(`position`,new G(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new Mo(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(I(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){I(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){I(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new Ci(i.x,i.y,{format:pn,type:$t,minFilter:Ut,magFilter:Ut,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new Is(i.x,i.y,Qt),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=ln,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=Bt,d.map.depthTexture.magFilter=Bt}else l.isPointLight?(d.map=new pu(i.x),d.map.depthTexture=new Ls(i.x,Zt)):(d.map=new Ci(i.x,i.y),d.map.depthTexture=new Is(i.x,i.y,Zt)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=ln,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=Ut,d.map.depthTexture.magFilter=Ut):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=Bt,d.map.depthTexture.magFilter=Bt);d.camera.updateProjectionMatrix()}let g=d.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<g;t++){if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),Ff.setFromMatrixPosition(l.matrixWorld),e.position.copy(Ff),If.copy(e.position),If.add(Mf[t]),e.up.copy(Nf[t]),e.lookAt(If),e.updateMatrixWorld(),n.makeTranslation(-Ff.x,-Ff.y,-Ff.z),Pf.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(Pf,e.coordinateSystem,e.reversedDepth)}else d.updateMatrices(l);r=d.getFrustum(),b(n,s,d.camera,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Ci(i.x,i.y,{format:pn,type:$t})),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function Rf(e,t){function n(){let t=!1,n=new xi,r=null,i=new xi(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?pe(e.DEPTH_TEST):me(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Ar[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?pe(e.STENCIL_TEST):me(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new W(0,0,0),T=0,E=!1,D=null,O=null,ee=null,k=null,te=null,ne=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),re=!1,ie=0,ae=e.getParameter(e.VERSION);ae.indexOf(`WebGL`)===-1?ae.indexOf(`OpenGL ES`)!==-1&&(ie=parseFloat(/^OpenGL ES (\d)/.exec(ae)[1]),re=ie>=2):(ie=parseFloat(/^WebGL (\d)/.exec(ae)[1]),re=ie>=1);let oe=null,se={},ce=e.getParameter(e.SCISSOR_BOX),le=e.getParameter(e.VIEWPORT),ue=new xi().fromArray(ce),de=new xi().fromArray(le);function fe(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let A={};A[e.TEXTURE_2D]=fe(e.TEXTURE_2D,e.TEXTURE_2D,1),A[e.TEXTURE_CUBE_MAP]=fe(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),A[e.TEXTURE_2D_ARRAY]=fe(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),A[e.TEXTURE_3D]=fe(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),pe(e.DEPTH_TEST),o.setFunc(3),xe(!1),Se(1),pe(e.CULL_FACE),ye(0);function pe(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function me(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function j(t,n){return f[t]===n?!1:(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function he(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function ge(t){return h===t?!1:(e.useProgram(t),h=t,!0)}let _e={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};_e[103]=e.MIN,_e[104]=e.MAX;let ve={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ye(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(me(e.BLEND),g=!1);return}if(g===!1&&(pe(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:L(`WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:L(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:L(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:L(`WebGLState: Invalid blending: `,t);break}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(_e[n],_e[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(ve[r],ve[i],ve[o],ve[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function be(t,n){t.side===2?me(e.CULL_FACE):pe(e.CULL_FACE);let r=t.side===1;n&&(r=!r),xe(r),t.blending===1&&t.transparent===!1?ye(0):ye(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Ce(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?pe(e.SAMPLE_ALPHA_TO_COVERAGE):me(e.SAMPLE_ALPHA_TO_COVERAGE)}function xe(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function Se(t){t===0?me(e.CULL_FACE):(pe(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function M(t){t!==ee&&(re&&e.lineWidth(t),ee=t)}function Ce(t,n,r){t?(pe(e.POLYGON_OFFSET_FILL),(k!==n||te!==r)&&(k=n,te=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):me(e.POLYGON_OFFSET_FILL)}function we(t){t?pe(e.SCISSOR_TEST):me(e.SCISSOR_TEST)}function Te(t){t===void 0&&(t=e.TEXTURE0+ne-1),oe!==t&&(e.activeTexture(t),oe=t)}function N(t,n,r){r===void 0&&(r=oe===null?e.TEXTURE0+ne-1:oe);let i=se[r];i===void 0&&(i={type:void 0,texture:void 0},se[r]=i),(i.type!==t||i.texture!==n)&&(oe!==r&&(e.activeTexture(r),oe=r),e.bindTexture(t,n||A[t]),i.type=t,i.texture=n)}function Ee(){let t=se[oe];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function P(){try{e.compressedTexImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function F(){try{e.compressedTexImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function De(){try{e.texSubImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Oe(){try{e.texSubImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function ke(){try{e.compressedTexSubImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Ae(){try{e.compressedTexSubImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function je(){try{e.texStorage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Me(){try{e.texStorage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Ne(){try{e.texImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Pe(){try{e.texImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Fe(t){return d[t]===void 0?e.getParameter(t):d[t]}function Ie(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Le(t){ue.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ue.copy(t))}function Re(t){de.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),de.copy(t))}function ze(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Be(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Ve(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},oe=null,se={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new W(0,0,0),T=0,E=!1,D=null,O=null,ee=null,k=null,te=null,ue.set(0,0,e.canvas.width,e.canvas.height),de.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:pe,disable:me,bindFramebuffer:j,drawBuffers:he,useProgram:ge,setBlending:ye,setMaterial:be,setFlipSided:xe,setCullFace:Se,setLineWidth:M,setPolygonOffset:Ce,setScissorTest:we,activeTexture:Te,bindTexture:N,unbindTexture:Ee,compressedTexImage2D:P,compressedTexImage3D:F,texImage2D:Ne,texImage3D:Pe,pixelStorei:Ie,getParameter:Fe,updateUBOMapping:ze,uniformBlockBinding:Be,texStorage2D:je,texStorage3D:Me,texSubImage2D:De,texSubImage3D:Oe,compressedTexSubImage2D:ke,compressedTexSubImage3D:Ae,scissor:Le,viewport:Re,reset:Ve}}function zf(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new z,u=new WeakMap,d=new Set,f,p=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Sr(`canvas`)}function g(e,t,n){let r=1,i=P(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),I(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&I(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];I(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||I(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?mr:ui.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,I(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function ee(){O=0}function k(){return O}function te(e){O=e}function ne(){let e=O;return e>=i.maxTextures&&I(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function re(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ie(t,i){let a=r.get(t);if(t.isVideoTexture&&N(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)I(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)I(`WebGLRenderer: Texture marked for update but image is incomplete`);else{me(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ae(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){me(a,t,i);return}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function oe(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){me(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function se(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){j(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let ce={[Lt]:e.REPEAT,[Rt]:e.CLAMP_TO_EDGE,[zt]:e.MIRRORED_REPEAT},le={[Bt]:e.NEAREST,[Vt]:e.NEAREST_MIPMAP_NEAREST,[Ht]:e.NEAREST_MIPMAP_LINEAR,[Ut]:e.LINEAR,[Wt]:e.LINEAR_MIPMAP_NEAREST,[Gt]:e.LINEAR_MIPMAP_LINEAR},ue={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function de(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&I(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,ce[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,ce[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,ce[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,le[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,le[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,ue[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function fe(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=re(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function A(e,t,n){return Math.floor(Math.floor(e/n)/t)}function pe(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=A(n.start,r.width,4),c=A(t.start,r.width,4);n.start<=i+1&&a===c&&A(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function me(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=fe(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=ui.getPrimaries(ui.workingColorSpace),r=o.colorSpace===``?null:ui.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Ee(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);de(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===un,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture)if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&pe(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data);else if(o.isCompressedTexture)if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023)if(r!==null)if(C){if(T)if(o.layerUpdates.size>0){let t=Pl(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0);else I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data)}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}else if(o.isDataArrayTexture)if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T)if(o.layerUpdates.size>0){let i=Pl(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w)if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}let r=e.RGBA,i=e.RGBA,a=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,r,i,a,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=P(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=P(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function j(t,o,s){if(o.image.length!==6)return;let c=fe(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=ui.getPrimaries(ui.workingColorSpace),r=o.colorSpace===``?null:ui.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Ee(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);de(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=P(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function he(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),Te(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,we(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function ge(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;Te(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,we(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,we(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);Te(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,we(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,we(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function _e(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),de(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else ie(i.depthTexture,0);let u=l.__webglTexture,d=we(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)Te(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)Te(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`Unknown depthTexture format`)}function ve(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer)if(a)for(let e=0;e<6;e++)_e(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?_e(i.__webglFramebuffer[0],t,0):_e(i.__webglFramebuffer,t,0)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),ge(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),ge(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function ye(t,n,i){let a=r.get(t);n!==void 0&&he(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&ve(t)}function be(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&Te(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=we(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),ge(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),de(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)he(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else he(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),de(c,a),he(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),de(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)he(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else he(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&ve(t)}function xe(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let Se=[],M=[];function Ce(t){if(t.samples>0){if(Te(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(Se.length=0,M.length=0,Se.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.resolveDepthBuffer===!1&&(Se.push(l),M.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,M)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,Se))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.resolveDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function we(e){return Math.min(i.maxSamples,e.samples)}function Te(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function N(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Ee(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(ui.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&I(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):L(`WebGLTextures: Unsupported texture color space:`,n)),t}function P(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=ne,this.resetTextureUnits=ee,this.getTextureUnits=k,this.setTextureUnits=te,this.setTexture2D=ie,this.setTexture2DArray=ae,this.setTexture3D=oe,this.setTextureCube=se,this.rebindTextures=ye,this.setupRenderTarget=be,this.updateRenderTargetMipmap=xe,this.updateMultisampleRenderTarget=Ce,this.setupDepthRenderbuffer=ve,this.setupFrameBufferTexture=he,this.useMultisampledRTT=Te,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Bf(e,t){function n(n,r=``){let i,a=ui.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var Vf=`
4080
+ }`,Mf=[new V(1,0,0),new V(-1,0,0),new V(0,1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1)],Nf=[new V(0,-1,0),new V(0,-1,0),new V(0,0,1),new V(0,0,-1),new V(0,-1,0),new V(0,-1,0)],Pf=new U,Ff=new V,If=new V;function Lf(e,t,n){let r=new fs,i=new z,a=new z,o=new xi,s=new ac,c=new oc,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new tc({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new z},radius:{value:4}},vertexShader:Af,fragmentShader:jf}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new K;m.setAttribute(`position`,new G(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new Mo(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(I(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){I(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){I(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new Ci(i.x,i.y,{format:pn,type:$t,minFilter:Ut,magFilter:Ut,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new Is(i.x,i.y,Qt),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=ln,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=Bt,d.map.depthTexture.magFilter=Bt}else l.isPointLight?(d.map=new pu(i.x),d.map.depthTexture=new Ls(i.x,Zt)):(d.map=new Ci(i.x,i.y),d.map.depthTexture=new Is(i.x,i.y,Zt)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=ln,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=Ut,d.map.depthTexture.magFilter=Ut):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=Bt,d.map.depthTexture.magFilter=Bt);d.camera.updateProjectionMatrix()}let g=d.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<g;t++){if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),Ff.setFromMatrixPosition(l.matrixWorld),e.position.copy(Ff),If.copy(e.position),If.add(Mf[t]),e.up.copy(Nf[t]),e.lookAt(If),e.updateMatrixWorld(),n.makeTranslation(-Ff.x,-Ff.y,-Ff.z),Pf.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(Pf,e.coordinateSystem,e.reversedDepth)}else d.updateMatrices(l);r=d.getFrustum(),b(n,s,d.camera,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Ci(i.x,i.y,{format:pn,type:$t})),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value=n.mapSize,f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function Rf(e,t){function n(){let t=!1,n=new xi,r=null,i=new xi(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?fe(e.DEPTH_TEST):pe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Ar[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?fe(e.STENCIL_TEST):pe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new W(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,re=0,ie=e.getParameter(e.VERSION);ie.indexOf(`WebGL`)===-1?ie.indexOf(`OpenGL ES`)!==-1&&(re=parseFloat(/^OpenGL ES (\d)/.exec(ie)[1]),ne=re>=2):(re=parseFloat(/^WebGL (\d)/.exec(ie)[1]),ne=re>=1);let ae=null,oe={},se=e.getParameter(e.SCISSOR_BOX),ce=e.getParameter(e.VIEWPORT),le=new xi().fromArray(se),ue=new xi().fromArray(ce);function de(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let j={};j[e.TEXTURE_2D]=de(e.TEXTURE_2D,e.TEXTURE_2D,1),j[e.TEXTURE_CUBE_MAP]=de(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),j[e.TEXTURE_2D_ARRAY]=de(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),j[e.TEXTURE_3D]=de(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),fe(e.DEPTH_TEST),o.setFunc(3),be(!1),xe(1),fe(e.CULL_FACE),ve(0);function fe(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function pe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function M(t,n){return f[t]===n?!1:(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function me(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function he(t){return h===t?!1:(e.useProgram(t),h=t,!0)}let ge={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ge[103]=e.MIN,ge[104]=e.MAX;let _e={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ve(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(pe(e.BLEND),g=!1);return}if(g===!1&&(fe(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:L(`WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:L(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:L(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:L(`WebGLState: Invalid blending: `,t);break}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(ge[n],ge[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(_e[r],_e[i],_e[o],_e[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function ye(t,n){t.side===2?pe(e.CULL_FACE):fe(e.CULL_FACE);let r=t.side===1;n&&(r=!r),be(r),t.blending===1&&t.transparent===!1?ve(0):ve(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Se(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?fe(e.SAMPLE_ALPHA_TO_COVERAGE):pe(e.SAMPLE_ALPHA_TO_COVERAGE)}function be(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function xe(t){t===0?pe(e.CULL_FACE):(fe(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function N(t){t!==k&&(ne&&e.lineWidth(t),k=t)}function Se(t,n,r){t?(fe(e.POLYGON_OFFSET_FILL),(A!==n||ee!==r)&&(A=n,ee=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):pe(e.POLYGON_OFFSET_FILL)}function Ce(t){t?fe(e.SCISSOR_TEST):pe(e.SCISSOR_TEST)}function we(t){t===void 0&&(t=e.TEXTURE0+te-1),ae!==t&&(e.activeTexture(t),ae=t)}function P(t,n,r){r===void 0&&(r=ae===null?e.TEXTURE0+te-1:ae);let i=oe[r];i===void 0&&(i={type:void 0,texture:void 0},oe[r]=i),(i.type!==t||i.texture!==n)&&(ae!==r&&(e.activeTexture(r),ae=r),e.bindTexture(t,n||j[t]),i.type=t,i.texture=n)}function Te(){let t=oe[ae];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function F(){try{e.compressedTexImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Ee(){try{e.compressedTexImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function De(){try{e.texSubImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Oe(){try{e.texSubImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function ke(){try{e.compressedTexSubImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Ae(){try{e.compressedTexSubImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function je(){try{e.texStorage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Me(){try{e.texStorage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Ne(){try{e.texImage2D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Pe(){try{e.texImage3D(...arguments)}catch(e){L(`WebGLState:`,e)}}function Fe(t){return d[t]===void 0?e.getParameter(t):d[t]}function Ie(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function Le(t){le.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),le.copy(t))}function Re(t){ue.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),ue.copy(t))}function ze(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Be(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Ve(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},ae=null,oe={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new W(0,0,0),T=0,E=!1,D=null,O=null,k=null,A=null,ee=null,le.set(0,0,e.canvas.width,e.canvas.height),ue.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:fe,disable:pe,bindFramebuffer:M,drawBuffers:me,useProgram:he,setBlending:ve,setMaterial:ye,setFlipSided:be,setCullFace:xe,setLineWidth:N,setPolygonOffset:Se,setScissorTest:Ce,activeTexture:we,bindTexture:P,unbindTexture:Te,compressedTexImage2D:F,compressedTexImage3D:Ee,texImage2D:Ne,texImage3D:Pe,pixelStorei:Ie,getParameter:Fe,updateUBOMapping:ze,uniformBlockBinding:Be,texStorage2D:je,texStorage3D:Me,texSubImage2D:De,texSubImage3D:Oe,compressedTexSubImage2D:ke,compressedTexSubImage3D:Ae,scissor:Le,viewport:Re,reset:Ve}}function zf(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new z,u=new WeakMap,d=new Set,f,p=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Sr(`canvas`)}function g(e,t,n){let r=1,i=F(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),I(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&I(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];I(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||I(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?mr:ui.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,I(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function S(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),T(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function w(e){let t=e.target;t.removeEventListener(`dispose`,w),D(t)}function T(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&E(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function E(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function D(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let O=0;function k(){O=0}function A(){return O}function ee(e){O=e}function te(){let e=O;return e>=i.maxTextures&&I(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),O+=1,e}function ne(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function re(t,i){let a=r.get(t);if(t.isVideoTexture&&P(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)I(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)I(`WebGLRenderer: Texture marked for update but image is incomplete`);else{pe(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ie(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function ae(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){pe(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function oe(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){M(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let se={[Lt]:e.REPEAT,[Rt]:e.CLAMP_TO_EDGE,[zt]:e.MIRRORED_REPEAT},ce={[Bt]:e.NEAREST,[Vt]:e.NEAREST_MIPMAP_NEAREST,[Ht]:e.NEAREST_MIPMAP_LINEAR,[Ut]:e.LINEAR,[Wt]:e.LINEAR_MIPMAP_NEAREST,[Gt]:e.LINEAR_MIPMAP_LINEAR},le={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function ue(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&I(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,se[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,se[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,se[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,ce[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,ce[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,le[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function de(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,C));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=ne(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&E(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function j(e,t,n){return Math.floor(Math.floor(e/n)/t)}function fe(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=j(n.start,r.width,4),c=j(t.start,r.width,4);n.start<=i+1&&a===c&&j(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function pe(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=de(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=ui.getPrimaries(ui.workingColorSpace),r=o.colorSpace===``?null:ui.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=Te(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);ue(c,o);let h,y=o.mipmaps,C=o.isVideoTexture!==!0,w=f.__version===void 0||l===!0,T=u.dataReady,E=S(o,t);if(o.isDepthTexture)m=x(o.format===un,o.type),w&&(C?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture)if(y.length>0){C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else C?(w&&n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height),T&&fe(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data);else if(o.isCompressedTexture)if(o.isCompressedArrayTexture){C&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023)if(r!==null)if(C){if(T)if(o.layerUpdates.size>0){let t=Pl(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0);else I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else C?T&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data)}else{C&&w&&n.texStorage2D(e.TEXTURE_2D,E,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}else if(o.isDataArrayTexture)if(C){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,E,m,t.width,t.height,t.depth),T)if(o.layerUpdates.size>0){let i=Pl(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isData3DTexture)C?(w&&n.texStorage3D(e.TEXTURE_3D,E,m,t.width,t.height,t.depth),T&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(w)if(C)n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<E;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}let r=e.RGBA,i=e.RGBA,a=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,r,i,a,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(C&&w){let t=F(y[0]);n.texStorage2D(e.TEXTURE_2D,E,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],C?T&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(C){if(w){let r=F(t);n.texStorage2D(e.TEXTURE_2D,E,m,r.width,r.height)}T&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function M(t,o,s){if(o.image.length!==6)return;let c=de(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=ui.getPrimaries(ui.workingColorSpace),r=o.colorSpace===``?null:ui.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=Te(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),C=b(o.internalFormat,y,x,o.normalized,o.colorSpace),w=o.isVideoTexture!==!0,T=u.__version===void 0||c===!0,E=l.dataReady,D=S(o,h);ue(e.TEXTURE_CUBE_MAP,o);let O;if(f){w&&T&&n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,h.width,h.height);for(let t=0;t<6;t++){O=m[t].mipmaps;for(let r=0;r<O.length;r++){let i=O[r];o.format===1023?w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,y,x,i.data):y===null?I(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):w?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,C,i.width,i.height,0,i.data)}}}else{if(O=o.mipmaps,w&&T){O.length>0&&D++;let t=F(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<O.length;r++){let i=O[r].image[t].image;w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,i.width,i.height,0,y,x,i.data)}}else{w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,y,x,m[t]);for(let r=0;r<O.length;r++){let i=O[r];w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,C,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function me(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function he(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function ge(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,C)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),ue(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else re(i.depthTexture,0);let u=l.__webglTexture,d=Ce(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`Unknown depthTexture format`)}function _e(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer)if(a)for(let e=0;e<6;e++)ge(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ge(i.__webglFramebuffer[0],t,0):ge(i.__webglFramebuffer,t,0)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),he(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),he(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function ve(t,n,i){let a=r.get(t);n!==void 0&&me(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&_e(t)}function ye(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,w);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&we(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Ce(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),he(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),ue(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)me(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),ue(c,a),me(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),ue(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)me(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else me(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&_e(t)}function be(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let xe=[],N=[];function Se(t){if(t.samples>0){if(we(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(xe.length=0,N.length=0,xe.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.resolveDepthBuffer===!1&&(xe.push(l),N.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,N)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,xe))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.resolveDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Ce(e){return Math.min(i.maxSamples,e.samples)}function we(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function P(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Te(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(ui.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&I(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):L(`WebGLTextures: Unsupported texture color space:`,n)),t}function F(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=te,this.resetTextureUnits=k,this.getTextureUnits=A,this.setTextureUnits=ee,this.setTexture2D=re,this.setTexture2DArray=ie,this.setTexture3D=ae,this.setTextureCube=oe,this.rebindTextures=ve,this.setupRenderTarget=ye,this.updateRenderTargetMipmap=be,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=_e,this.setupFrameBufferTexture=me,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Bf(e,t){function n(n,r=``){let i,a=ui.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var Vf=`
4081
4081
  void main() {
4082
4082
 
4083
4083
  gl_Position = vec4( position, 1.0 );
@@ -4101,7 +4101,7 @@ void main() {
4101
4101
 
4102
4102
  }
4103
4103
 
4104
- }`,Uf=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Rs(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new tc({vertexShader:Vf,fragmentShader:Hf,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Mo(new Gs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Wf=class extends jr{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new Uf,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new z,C=null,w=new Xc;w.viewport=new xi;let T=new Xc;T.viewport=new xi;let E=[w,T],D=new dl,O=null,ee=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getHandSpace()};function k(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function te(){r.removeEventListener(`select`,k),r.removeEventListener(`selectstart`,k),r.removeEventListener(`selectend`,k),r.removeEventListener(`squeeze`,k),r.removeEventListener(`squeezestart`,k),r.removeEventListener(`squeezeend`,k),r.removeEventListener(`end`,te),r.removeEventListener(`inputsourceschange`,ne);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}O=null,ee=null,h.reset();for(let e in g)delete g[e];e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,ue.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&I(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&I(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,k),r.addEventListener(`selectstart`,k),r.addEventListener(`selectend`,k),r.addEventListener(`squeeze`,k),r.addEventListener(`squeezestart`,k),r.addEventListener(`squeezeend`,k),r.addEventListener(`end`,te),r.addEventListener(`inputsourceschange`,ne),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?un:ln,a=_.stencil?nn:Zt);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new Ci(d.textureWidth,d.textureHeight,{format:cn,type:Kt,depthTexture:new Is(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ci(f.framebufferWidth,f.framebufferHeight,{format:cn,type:Kt,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),ue.setContext(r),ue.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function ne(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let re=new V,ie=new V;function ae(e,t,n){re.setFromMatrixPosition(t.matrixWorld),ie.setFromMatrixPosition(n.matrixWorld);let r=re.distanceTo(ie),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function oe(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,(O!==D.near||ee!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,ee=D.far),D.layers.mask=e.layers.mask|6,w.layers.mask=D.layers.mask&-5,T.layers.mask=D.layers.mask&-3;let i=e.parent,a=D.cameras;oe(D,i);for(let e=0;e<a.length;e++)oe(a[e],i);a.length===2?ae(D,w,T):D.projectionMatrix.copy(w.projectionMatrix),se(e,D,i)};function se(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=Fr*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(D)},this.getCameraTexture=function(e){return g[e]};let ce=null;function le(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==D.cameras.length&&(D.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=E[n];o===void 0&&(o=new Xc,o.layers.enable(n),o.viewport=new xi,E[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(D.matrix.copy(o.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),i===!0&&D.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new Rs,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}ce&&ce(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let ue=new Il;ue.setAnimationLoop(le),this.setAnimationLoop=function(e){ce=e},this.dispose=function(){}}},Gf=new U,Kf=new H;Kf.set(-1,0,0,0,1,0,0,0,1);function qf(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Zs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(Gf.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(Kf),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function Jf(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return L(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):ArrayBuffer.isView(o)?i.__data.set(new o.constructor(o.buffer,o.byteOffset,i.__data.length)):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:ArrayBuffer.isView(i)?r[a]=i.slice():r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?I(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):I(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var Yf=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Xf=null;function Zf(){return Xf===null&&(Xf=new Ko(Yf,16,16,pn,$t),Xf.name=`DFG_LUT`,Xf.minFilter=Ut,Xf.magFilter=Ut,Xf.wrapS=Rt,Xf.wrapT=Rt,Xf.generateMipmaps=!1,Xf.needsUpdate=!0),Xf}var Qf=class{constructor(e={}){let{canvas:t=Cr(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Kt}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([hn,mn,fn]),g=new Set([Kt,Zt,Yt,nn,en,tn]),_=new Uint32Array(4),v=new Int32Array(4),y=new V,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null;this._outputColorSpace=fr;let O=0,ee=0,k=null,te=-1,ne=null,re=new xi,ie=new xi,ae=null,oe=new W(0),se=0,ce=t.width,le=t.height,ue=1,de=null,fe=null,A=new xi(0,0,ce,le),pe=new xi(0,0,ce,le),me=!1,j=new fs,he=!1,ge=!1,_e=new U,ve=new V,ye=new xi,be={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},xe=!1;function Se(){return k===null?ue:1}let M=n;function Ce(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r184`),t.addEventListener(`webglcontextlost`,Ke,!1),t.addEventListener(`webglcontextrestored`,qe,!1),t.addEventListener(`webglcontextcreationerror`,Je,!1),M===null){let t=`webgl2`;if(M=Ce(t,e),M===null)throw Ce(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw L(`WebGLRenderer: `+e.message),e}let we,Te,N,Ee,P,F,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue;function We(){we=new hu(M),we.init(),Ve=new Bf(M,we),Te=new Gl(M,we,e,Ve),N=new Rf(M,we),Te.reversedDepthBuffer&&d&&N.buffers.depth.setReversed(!0),Ee=new vu(M),P=new vf,F=new zf(M,we,N,P,Te,Ve,Ee),De=new mu(T),Oe=new Ll(M),He=new Ul(M,Oe),ke=new gu(M,Oe,Ee,He),Ae=new bu(M,ke,Oe,He,Ee),Re=new yu(M,Te,F),Fe=new Kl(P),je=new _f(T,De,we,Te,He,Fe),Me=new qf(T,P),Ne=new Sf,Pe=new kf(we),Le=new Hl(T,De,N,Ae,p,s),Ie=new Lf(T,Ae,Te),Ue=new Jf(M,Ee,Te,N),ze=new Wl(M,we,Ee),Be=new _u(M,we,Ee),Ee.programs=je.programs,T.capabilities=Te,T.extensions=we,T.properties=P,T.renderLists=Ne,T.shadowMap=Ie,T.state=N,T.info=Ee}We(),m!==1009&&(w=new Su(m,t.width,t.height,r,i));let Ge=new Wf(T,M);this.xr=Ge,this.getContext=function(){return M},this.getContextAttributes=function(){return M.getContextAttributes()},this.forceContextLoss=function(){let e=we.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=we.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return ue},this.setPixelRatio=function(e){e!==void 0&&(ue=e,this.setSize(ce,le,!1))},this.getSize=function(e){return e.set(ce,le)},this.setSize=function(e,n,r=!0){if(Ge.isPresenting){I(`WebGLRenderer: Can't change size while VR device is presenting.`);return}ce=e,le=n,t.width=Math.floor(e*ue),t.height=Math.floor(n*ue),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(ce*ue,le*ue).floor()},this.setDrawingBufferSize=function(e,n,r){ce=e,le=n,ue=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){L(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){I(`THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(re)},this.getViewport=function(e){return e.copy(A)},this.setViewport=function(e,t,n,r){e.isVector4?A.set(e.x,e.y,e.z,e.w):A.set(e,t,n,r),N.viewport(re.copy(A).multiplyScalar(ue).round())},this.getScissor=function(e){return e.copy(pe)},this.setScissor=function(e,t,n,r){e.isVector4?pe.set(e.x,e.y,e.z,e.w):pe.set(e,t,n,r),N.scissor(ie.copy(pe).multiplyScalar(ue).round())},this.getScissorTest=function(){return me},this.setScissorTest=function(e){N.setScissorTest(me=e)},this.setOpaqueSort=function(e){de=e},this.setTransparentSort=function(e){fe=e},this.getClearColor=function(e){return e.copy(Le.getClearColor())},this.setClearColor=function(){Le.setClearColor(...arguments)},this.getClearAlpha=function(){return Le.getClearAlpha()},this.setClearAlpha=function(){Le.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(k!==null){let t=k.texture.format;e=h.has(t)}if(e){let e=k.texture.type,t=g.has(e),n=Le.getClearColor(),r=Le.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,M.clearBufferuiv(M.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,M.clearBufferiv(M.COLOR,0,v))}else r|=M.COLOR_BUFFER_BIT}t&&(r|=M.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=M.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&M.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,Ke,!1),t.removeEventListener(`webglcontextrestored`,qe,!1),t.removeEventListener(`webglcontextcreationerror`,Je,!1),Le.dispose(),Ne.dispose(),Pe.dispose(),P.dispose(),De.dispose(),Ae.dispose(),He.dispose(),Ue.dispose(),je.dispose(),Ge.dispose(),Ge.removeEventListener(`sessionstart`,tt),Ge.removeEventListener(`sessionend`,nt),rt.stop()};function Ke(e){e.preventDefault(),Er(`WebGLRenderer: Context Lost.`),E=!0}function qe(){Er(`WebGLRenderer: Context Restored.`),E=!1;let e=Ee.autoReset,t=Ie.enabled,n=Ie.autoUpdate,r=Ie.needsUpdate,i=Ie.type;We(),Ee.autoReset=e,Ie.enabled=t,Ie.autoUpdate=n,Ie.needsUpdate=r,Ie.type=i}function Je(e){L(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Ye(e){let t=e.target;t.removeEventListener(`dispose`,Ye),Xe(t)}function Xe(e){Ze(e),P.remove(e)}function Ze(e){let t=P.get(e).programs;t!==void 0&&(t.forEach(function(e){je.releaseProgram(e)}),e.isShaderMaterial&&je.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=be);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=pt(e,t,n,r,i);N.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=ke.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;He.setup(i,r,s,n,c);let h,g=ze;if(c!==null&&(h=Oe.get(c),g=Be,g.setIndex(h)),i.isMesh)r.wireframe===!0?(N.setLineWidth(r.wireframeLinewidth*Se()),g.setMode(M.LINES)):g.setMode(M.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),N.setLineWidth(e*Se()),i.isLineSegments?g.setMode(M.LINES):i.isLineLoop?g.setMode(M.LINE_LOOP):g.setMode(M.LINE_STRIP)}else i.isPoints?g.setMode(M.POINTS):i.isSprite&&g.setMode(M.TRIANGLES);if(i.isBatchedMesh)if(we.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Oe.get(c).bytesPerElement:1,o=P.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(M,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Qe(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,lt(e,t,n),e.side=0,e.needsUpdate=!0,lt(e,t,n),e.side=2):lt(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),x=Pe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Qe(a,n,e),r.add(a)}else Qe(t,n,e),r.add(t)}),x=C.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){P.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}we.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let $e=null;function et(e){$e&&$e(e)}function tt(){rt.stop()}function nt(){rt.start()}let rt=new Il;rt.setAnimationLoop(et),typeof self<`u`&&rt.setContext(self),this.setAnimationLoop=function(e){$e=e,Ge.setAnimationLoop(e),e===null?rt.stop():rt.start()},Ge.addEventListener(`sessionstart`,tt),Ge.addEventListener(`sessionend`,nt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){L(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ge.enabled===!0&&Ge.isPresenting===!0,r=w!==null&&(k===null||n)&&w.begin(T,k);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ge.enabled===!0&&Ge.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ge.cameraAutoUpdate===!0&&Ge.updateCamera(t),t=Ge.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,k),x=Pe.get(e,C.length),x.init(t),x.state.textureUnits=F.getTextureUnits(),C.push(x),_e.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),j.setFromProjectionMatrix(_e,yr,t.reversedDepth),ge=this.localClippingEnabled,he=Fe.init(this.clippingPlanes,ge),b=Ne.get(e,S.length),b.init(),S.push(b),Ge.enabled===!0&&Ge.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&it(e,t,-1/0,T.sortObjects)}it(e,t,0,T.sortObjects),b.finish(),T.sortObjects===!0&&b.sort(de,fe),xe=Ge.enabled===!1||Ge.isPresenting===!1||Ge.hasDepthSensing()===!1,xe&&Le.addToRenderList(b,e),this.info.render.frame++,he===!0&&Fe.beginShadows();let i=x.state.shadowsArray;if(Ie.render(i,e,t),he===!0&&Fe.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];ot(n,r,e,a)}xe&&Le.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];at(b,e,n,n.viewport)}}else r.length>0&&ot(n,r,e,t),xe&&Le.render(e),at(b,e,t)}k!==null&&ee===0&&(F.updateMultisampleRenderTarget(k),F.updateRenderTargetMipmap(k)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),He.resetDefaultState(),te=-1,ne=null,C.pop(),C.length>0?(x=C[C.length-1],F.setTextureUnits(x.state.textureUnits),he===!0&&Fe.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function it(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||j.intersectsSprite(e)){r&&ye.setFromMatrixPosition(e.matrixWorld).applyMatrix4(_e);let t=Ae.update(e),i=e.material;i.visible&&b.push(e,t,i,n,ye.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||j.intersectsObject(e))){let t=Ae.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),ye.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),ye.copy(e.boundingSphere.center)),ye.applyMatrix4(e.matrixWorld).applyMatrix4(_e)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&b.push(e,t,s,n,ye.z,o)}}else i.visible&&b.push(e,t,i,n,ye.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)it(i[e],t,n,r)}function at(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),he===!0&&Fe.setGlobalState(T.clippingPlanes,n),r&&N.viewport(re.copy(r)),i.length>0&&st(i,t,n),a.length>0&&st(a,t,n),o.length>0&&st(o,t,n),N.buffers.depth.setTest(!0),N.buffers.depth.setMask(!0),N.buffers.color.setMask(!0),N.setPolygonOffset(!1)}function ot(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=we.has(`EXT_color_buffer_half_float`)||we.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new Ci(1,1,{generateMipmaps:!0,type:e?$t:Kt,minFilter:Gt,samples:Math.max(4,Te.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ui.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||re;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(oe),se=T.getClearAlpha(),se<1&&T.setClearColor(16777215,.5),T.clear(),xe&&Le.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),he===!0&&Fe.setGlobalState(T.clippingPlanes,r),st(e,n,r),F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a),we.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,ct(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(oe,se),d!==void 0&&(r.viewport=d),T.toneMapping=u}function st(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&ct(o,t,n,s,l,c)}}function ct(e,t,n,r,i,a){e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function lt(e,t,n){t.isScene!==!0&&(t=be);let r=P.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=je.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=je.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=De.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Ye),l=new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return dt(e,s),d}else s.uniforms=je.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=je.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Fe.uniform),dt(e,s),r.needsLights=ht(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function ut(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=kd.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function dt(e,t){let n=P.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ft(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function pt(e,t,n,r,i){t.isScene!==!0&&(t=be),F.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=k===null?T.outputColorSpace:k.isXRRenderTarget===!0?k.texture.colorSpace:ui.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=De.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(k===null||k.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=P.get(r),y=x.state.lights;if(he===!0&&(ge===!0||e!==ne)){let t=e===ne&&r.id===te;Fe.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Fe.numPlanes||v.numIntersection!==Fe.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=lt(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),ee=v.uniforms;if(N.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==te&&(te=r.id,w=!0),v.needsLights){let e=ft(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||ne!==e){N.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(M,`projectionMatrix`,e.projectionMatrix),O.setValue(M,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(M,ve.setFromMatrixPosition(e.matrixWorld)),Te.logarithmicDepthBuffer&&O.setValue(M,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(M,`isOrthographic`,e.isOrthographicCamera===!0),ne!==e&&(ne=e,w=!0,E=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&O.setValue(M,`directionalShadowMap`,y.state.directionalShadowMap,F),y.state.spotShadowMap.length>0&&O.setValue(M,`spotShadowMap`,y.state.spotShadowMap,F),y.state.pointShadowMap.length>0&&O.setValue(M,`pointShadowMap`,y.state.pointShadowMap,F)),i.isSkinnedMesh){O.setOptional(M,i,`bindMatrix`),O.setOptional(M,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(M,`boneTexture`,e.boneTexture,F))}i.isBatchedMesh&&(O.setOptional(M,i,`batchingTexture`),O.setValue(M,`batchingTexture`,i._matricesTexture,F),O.setOptional(M,i,`batchingIdTexture`),O.setValue(M,`batchingIdTexture`,i._indirectTexture,F),O.setOptional(M,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(M,`batchingColorTexture`,i._colorsTexture,F));let re=n.morphAttributes;if((re.position!==void 0||re.normal!==void 0||re.color!==void 0)&&Re.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(M,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(ee.envMapIntensity.value=t.environmentIntensity),ee.dfgLUT!==void 0&&(ee.dfgLUT.value=Zf()),w){if(O.setValue(M,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&mt(ee,E),a&&r.fog===!0&&Me.refreshFogUniforms(ee,a),Me.refreshMaterialUniforms(ee,r,ue,le,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;ee.probesSH.value=e.texture,ee.probesMin.value.copy(e.boundingBox.min),ee.probesMax.value.copy(e.boundingBox.max),ee.probesResolution.value.copy(e.resolution)}kd.upload(M,ut(v),ee,F)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(kd.upload(M,ut(v),ee,F),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(M,`center`,i.center),O.setValue(M,`modelViewMatrix`,i.modelViewMatrix),O.setValue(M,`normalMatrix`,i.normalMatrix),O.setValue(M,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ue.update(n,S),Ue.bind(n,S)}}return S}function mt(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function ht(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return O},this.getActiveMipmapLevel=function(){return ee},this.getRenderTarget=function(){return k},this.setRenderTargetTextures=function(e,t,n){let r=P.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),P.get(e.texture).__webglTexture=t,P.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=P.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let gt=M.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){k=e,O=t,ee=n;let r=null,i=!1,a=!1;if(e){let o=P.get(e);if(o.__useDefaultFramebuffer!==void 0){N.bindFramebuffer(M.FRAMEBUFFER,o.__webglFramebuffer),re.copy(e.viewport),ie.copy(e.scissor),ae=e.scissorTest,N.viewport(re),N.scissor(ie),N.setScissorTest(ae),te=-1;return}else if(o.__webglFramebuffer===void 0)F.setupRenderTarget(e);else if(o.__hasExternalTextures)F.rebindTextures(e,P.get(e.texture).__webglTexture,P.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&P.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);F.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=P.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&F.useMultisampledRTT(e)===!1?P.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,re.copy(e.viewport),ie.copy(e.scissor),ae=e.scissorTest}else re.copy(A).multiplyScalar(ue).floor(),ie.copy(pe).multiplyScalar(ue).floor(),ae=me;if(n!==0&&(r=gt),N.bindFramebuffer(M.FRAMEBUFFER,r)&&N.drawBuffers(e,r),N.viewport(re),N.scissor(ie),N.setScissorTest(ae),i){let r=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=P.get(e.textures[t]);M.framebufferTextureLayer(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,t.__webglTexture,n)}te=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){N.bindFramebuffer(M.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),!Te.textureFormatReadable(c)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!Te.textureTypeReadable(l)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&M.readPixels(t,n,r,i,Ve.convert(c),Ve.convert(l),a)}finally{let e=k===null?null:P.get(k).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){N.bindFramebuffer(M.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),!Te.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!Te.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=M.createBuffer();M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.bufferData(M.PIXEL_PACK_BUFFER,a.byteLength,M.STREAM_READ),M.readPixels(t,n,r,i,Ve.convert(l),Ve.convert(u),0);let f=k===null?null:P.get(k).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,f);let p=M.fenceSync(M.SYNC_GPU_COMMANDS_COMPLETE,0);return M.flush(),await kr(M,p,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,a),M.deleteBuffer(d),M.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;F.setTexture2D(e,0),M.copyTexSubImage2D(M.TEXTURE_2D,n,0,0,o,s,i,a),N.unbindTexture()};let _t=M.createFramebuffer(),vt=M.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Ve.convert(t.format),_=Ve.convert(t.type),v;t.isData3DTexture?(F.setTexture3D(t,0),v=M.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(F.setTexture2DArray(t,0),v=M.TEXTURE_2D_ARRAY):(F.setTexture2D(t,0),v=M.TEXTURE_2D),N.activeTexture(M.TEXTURE0),N.pixelStorei(M.UNPACK_FLIP_Y_WEBGL,t.flipY),N.pixelStorei(M.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),N.pixelStorei(M.UNPACK_ALIGNMENT,t.unpackAlignment);let y=N.getParameter(M.UNPACK_ROW_LENGTH),b=N.getParameter(M.UNPACK_IMAGE_HEIGHT),x=N.getParameter(M.UNPACK_SKIP_PIXELS),S=N.getParameter(M.UNPACK_SKIP_ROWS),C=N.getParameter(M.UNPACK_SKIP_IMAGES);N.pixelStorei(M.UNPACK_ROW_LENGTH,h.width),N.pixelStorei(M.UNPACK_IMAGE_HEIGHT,h.height),N.pixelStorei(M.UNPACK_SKIP_PIXELS,l),N.pixelStorei(M.UNPACK_SKIP_ROWS,u),N.pixelStorei(M.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=P.get(e),r=P.get(t),h=P.get(n.__renderTarget),g=P.get(r.__renderTarget);N.bindFramebuffer(M.READ_FRAMEBUFFER,h.__webglFramebuffer),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(e).__webglTexture,i,d+n),M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(t).__webglTexture,a,m+n)),M.blitFramebuffer(l,u,o,s,f,p,o,s,M.DEPTH_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||P.has(e)){let n=P.get(e),r=P.get(t);N.bindFramebuffer(M.READ_FRAMEBUFFER,_t),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,vt);for(let e=0;e<c;e++)w?M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):M.framebufferTexture2D(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,n.__webglTexture,i),T?M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):M.framebufferTexture2D(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,r.__webglTexture,a),i===0?T?M.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):M.copyTexSubImage2D(v,a,f,p,l,u,o,s):M.blitFramebuffer(l,u,o,s,f,p,o,s,M.COLOR_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?M.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?M.compressedTexSubImage2D(M.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h);N.pixelStorei(M.UNPACK_ROW_LENGTH,y),N.pixelStorei(M.UNPACK_IMAGE_HEIGHT,b),N.pixelStorei(M.UNPACK_SKIP_PIXELS,x),N.pixelStorei(M.UNPACK_SKIP_ROWS,S),N.pixelStorei(M.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&M.generateMipmap(v),N.unbindTexture()},this.initRenderTarget=function(e){P.get(e).__webglFramebuffer===void 0&&F.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?F.setTextureCube(e,0):e.isData3DTexture?F.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?F.setTexture2DArray(e,0):F.setTexture2D(e,0),N.unbindTexture()},this.resetState=function(){O=0,ee=0,k=null,N.reset(),He.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return yr}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=ui._getDrawingBufferColorSpace(e),t.unpackColorSpace=ui._getUnpackColorSpace()}},$f=class{entries=new Map;loader;constructor(e){this.loader=e??((e,t)=>new Lc().load(e,()=>t?.onLoad?.(),void 0,e=>t?.onError?.(e)))}load(e){for(let[t,n]of Object.entries(e)){let e=n.type;if(e!==`texture`&&e!==`spritesheet`)throw new y(`BAD_FORMAT`,`Asset '${t}': "type" must be 'texture' or 'spritesheet', got ${JSON.stringify(e)}.`);if(typeof n.url!=`string`||n.url===``)throw new y(`BAD_FORMAT`,`Asset '${t}': "url" must be a non-empty string.`);let r,i;if(e===`spritesheet`){if(typeof n.frameWidth!=`number`||typeof n.frameHeight!=`number`)throw new y(`BAD_FORMAT`,`Asset '${t}': spritesheets need numeric "frameWidth" and "frameHeight".`);r=n.frameWidth,i=n.frameHeight}let a=this.entries.get(t),o={status:`loading`},s=this.loader(n.url,{onLoad:()=>{o.status=`ready`},onError:e=>{o.status=`error`,console.error(`[incanto] failed to load texture '${t}' (${n.url}):`,e)}});a&&a.texture!==s&&a.texture.dispose(),s.colorSpace=fr,n.filter===`nearest`?(s.magFilter=Bt,s.minFilter=Bt,s.generateMipmaps=!1):s.magFilter=Ut,s.needsUpdate=!0,this.entries.set(t,{texture:s,type:e,frameWidth:r,frameHeight:i,state:o})}}status(e){return this.entries.get(e)?.state.status}getTexture(e){return this.resolve(e).texture}getSheet(e){let t=this.resolve(e);if(t.type!==`spritesheet`)throw new y(`BAD_FORMAT`,`Asset '${e}' is a plain texture; a spritesheet (with frameWidth/frameHeight) is required here.`);return{texture:t.texture,frameWidth:t.frameWidth,frameHeight:t.frameHeight}}resolve(e){if(!e.startsWith(`$`))throw new y(`UNKNOWN_ASSET`,`Asset reference '${e}' must use the '$key' form (e.g. '$${e}').`);let t=this.entries.get(e.slice(1));if(!t)throw new y(`UNKNOWN_ASSET`,`Unknown asset '${e}'. Declared assets: [${[...this.entries.keys()].join(`, `)}].`);return t}};function ep(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new y(`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 y(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new y(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var tp=class extends Fe{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 rt(this.orderGroup,this.renderOrder)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new Qi}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ri.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}},np=class extends tp{static props={collider:{default:{}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){ep(e.collider,e.name)}_physics=null},rp=class extends np{static typeName=`StaticBody2D`},ip=class extends np{static typeName=`Area2D`},ap=class extends np{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]},op=class extends np{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 y(`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)}isOnFloor(){return this._grounded}},sp=new Set;function cp(e){return sp.add(e),()=>sp.delete(e)}function lp(e){return[...sp].filter(t=>t.dimension===e)}var up=class extends tp{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``},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 np))throw new y(`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 y(`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 np))throw new y(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},dp=`modulepreload`,fp=function(e,t){return new URL(e,t).href},pp={},mp=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=fp(t,n),t in pp)return;pp[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:dp,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Y=100,hp=Math.PI/180;async function gp(e,t){let n=await mp(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init(),new _p(n,e,t)}var _p=class{R;engine;debugDraw=!1;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.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Y,y:(i[1]??0)/Y}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=cp(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}step(e){if(this.lastDt=e,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)/Y,y:(e[1]??0)/Y}}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]=wp(e);e.position=[n.x*Y-t,n.y*Y-r]}if(e instanceof ap){e.fixedRotation||(e.rotation=t.body.rotation()/hp);let n=t.body.linvel();e.linearVelocity=[n.x*Y,n.y*Y],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let[r,i]=Cp(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`;r.emit(a,i),i.emit(a,r)})}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*hp);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=Cp(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)/Y*1,y:(n*this.lastDt+i)/Y*1},o=t.body.translation().y*Y+xp(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>Sp(r)+bp))});let s=this.kcc.computedMovement(),c=t.body.translation();if(t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=(c.x+s.x)*Y,r=(c.y+s.y)*Y+xp(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof op)){t.ground=i.node;let[e,n]=Cp(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.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Y;return 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)/Y,y:(e.anchor[1]??0)/Y},s={x:(e.targetAnchor[0]??0)/Y,y:(e.targetAnchor[1]??0)/Y},c=e.length/Y;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]/Y,y:e[1]/Y},{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/Y,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Y,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;syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=t!==this.lastStructure||e.root!==this.lastRoot;n&&(this.lastStructure=t,this.lastRoot=e.root,this.bodySet.clear(),yp(e.root,this.bodySet)),n&&(this.jointSet.clear(),vp(e.root,this.jointSet));let r=this.bodySet;for(let e of r){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),console.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(n),n)for(let[e,t]of this.entries)r.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]=Cp(e),a=r/Y,o=i/Y,s;s=e instanceof ap?n.RigidBodyDesc.dynamic():e instanceof op||e instanceof ip?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*hp),e instanceof ap&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Y,(e.linearVelocity[1]??0)/Y),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=Tp(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof ip&&l.setSensor(!0),e instanceof ap&&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]=Cp(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Y,y:i/Y},!0),t.lastX=r,t.lastY=i),e instanceof ap){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Y,y:r/Y},!0),t.lastVX=n,t.lastVY=r)}return t}};function vp(e,t){e instanceof up&&t.add(e);for(let n of e.children)vp(n,t)}function yp(e,t){e instanceof np&&t.add(e);for(let n of e.children)yp(n,t)}var bp=4;function xp(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 Sp(e){let[,t]=Cp(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 Cp(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof tp&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function wp(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof tp&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Tp(e,t,n){ep(t,n);let r=Ep(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Y,(i[1]??0)/Y),r}function Ep(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 y(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Y,r[1]/2/Y)}if(r===`circle`){if(typeof t.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Y)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Y,t.radius/Y)}throw new y(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}var Dp=new Gs(1,1),Op=class extends tp{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 Mo(Dp,new bo({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}},kp=class extends Op{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 y(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=Ap(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 Ap(e,t){if(!Array.isArray(e)||e.length===0)throw new y(`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 jp=class extends tp{static typeName=`Camera2D`;static props={follow:{default:``},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 tp))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 y(`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=Mp(n,i+c,o-c),r=Mp(r,a+l,s-l)}return{x:n,y:r}}};function Mp(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var Np=class extends Fe{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`}};mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;onReady(){if(!(this.parent instanceof op))throw new y(`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 y(`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 op))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;if(n.velocity[0]=i.x*this.maxSpeed,n.isOnFloor()){let e=r.justPressed(this.jumpAction);n.velocity[1]=e?-Math.sqrt(2*a*this.jumpHeight):20}else n.velocity[1]=(n.velocity[1]??0)+a*e;n.moveAndSlide()}},Pp=new Gs(1,1),Fp=class extends tp{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 Mo(Pp,new bo({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}},Ip=new Gs(1,1),Lp=class extends tp{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 Mo(Ip,new bo({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 Fs(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)}},Rp=new Gs(1,1),zp=class e extends tp{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`,...at]},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`&&!at.includes(t.preset))throw new y(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${at.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:at});if(t.blend!==`add`&&t.blend!==`normal`)throw new y(`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){ot(this,this.preset,_e(e.typeName));let t=this.tree?.engine?.rng??new b(4660);this.sim=new ct({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 W,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 bo({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new is(Rp,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(vr),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:Vp.set(this.colorStart),a=Hp.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Bp.makeScale(t,t,1),Bp.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Bp);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))),Up.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,Up),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Bp=new U,Vp=new W,Hp=new W,Up=new W;function Wp(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 y(`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 Gp(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 Kp=class extends tp{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;Wp(t._cells,t._legend)}grid(){return Wp(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;Gp(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new rp(`__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 Mo(new K,new bo({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=Bt,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 G(new Float32Array(a),3)),e.setAttribute(`uv`,new G(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()}},qp=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Jp=class extends Fe{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:qp}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new $i,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!qp.includes(t))throw new y(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${qp.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:qp})}_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 Yp(){lt(),j(tp),j(Op),j(Fp),j(zp),j(kp),j(jp),j(Lp),j(Jp),j(rp),j(ap),j(ip),j(op),j(Np),j(up),j(Kp)}function Xp(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Zp(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Qp=new Ca,$p=new V,em=12,tm=new Float32Array(16);function nm(e){if(!(e instanceof tp))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Qp.setFromObject(t),Qp.getSize($p);let n,r,i,a;if(!Number.isFinite($p.x)||$p.x===0&&$p.y===0){let e=new V().setFromMatrixPosition(t.matrixWorld);n=e.x-em,i=e.x+em,r=e.y-em,a=e.y+em}else n=Qp.min.x-2,i=Qp.max.x+2,r=Qp.min.y-2,a=Qp.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return tm.set(o),tm}function rm(){return{visited:new Set,cameras:[]}}function im(e,t,n,r,i,a,o){let s=a??rm();s.visited.clear(),s.cameras.length=0,am(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),om(t,s.visited),om(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 am(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof tp&&!(e instanceof Jp)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Jp){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 tp){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof jp&&!r&&a.push(e),l=n}for(let t of e.children)am(t,l,n,u,i,a,o,s,c);if(e instanceof tp&&!(e instanceof Jp)){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 om(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&&om(i,t)}}var sm=class{viewOverride=null;webgl;worldScene=new ca;syncScratch=rm();ignoreStatic=!1;uiScene=new ca;worldCam=new tl(-1,1,1,-1,-1e3,1e3);uiCam=new tl(-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 $f;let t=ut(e.engine.scene?.environment,{antialias:!0,pixelRatio:1},globalThis.devicePixelRatio??1,e);this.webgl=new Qf({canvas:e.canvas,antialias:t.antialias}),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Ts(new K,new ps({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 Ts(new K,new ps({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?nm(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 G(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of lp(`2d`))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 G(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 W(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(lm);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:_t(e.viewport),o=a?vt(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=im(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)),cm(this.worldCam,u.x,u.y,s/d,c/d),cm(this.uiCam,s/2,c/2,s,c),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 Zp(this.lastView,e,t)}screenFromWorld(e,t){return Xp(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;dm.set((e-i)/o*2-1,-((t-a)/s*2-1)),fm.setFromCamera(dm,this.worldCam);let c=fm.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||(pm.makeEmpty(),pm.expandByObject(t),pm.isEmpty())||(pm.getSize(um),um.x===0&&um.y===0))return null;let n=this.screenFromWorld(pm.min.x,-pm.max.y),r=this.screenFromWorld(pm.max.x,-pm.min.y);return{x:n.x,y:n.y,w:r.x-n.x,h:r.y-n.y}}dispose(){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 cm(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 lm=new z,um=new V,dm=new z,fm=new Al,pm=new Ca,mm=e({enablePhysics2D:()=>gp}),hm=(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())}),gm=(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())}),_m=class extends Qi{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 vm(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 ym(e,t){return gm(this,null,function*(){return vm(e,t,yield e.parser.getDependency(`node`,t))})}function bm(e){return gm(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=vm(e,r,t);i!=null&&n.set(r,i)}),n})}var xm={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 Sm(e){return Math.max(Math.min(e,1),0)}var Cm=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(xm));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(xm));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=Sm(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}}},wm={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},Tm={_Color:wm.Color,_EmissionColor:wm.EmissionColor,_ShadeColor:wm.ShadeColor,_RimColor:wm.RimColor,_OutlineColor:wm.OutlineColor},Em=new W,Dm=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(Em.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 W(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}};Dm._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 Om=Dm,km=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)})}},Am=new z,jm=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(Am.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(Am.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))})}};jm._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Mm=jm,Nm=new Set([`1.0`,`1.0-beta`]),Pm=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return gm(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return gm(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(!Nm.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(xm)),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 Cm;return yield Promise.all(Array.from(o.entries()).map(t=>gm(this,[t],function*([t,n]){var r,i,a;let o=new _m(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=>gm(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield ym(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 km({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=>gm(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Om({material:t,type:e.type,targetValue:new W().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>gm(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Mm({material:t,offset:new z().fromArray(e.offset??[0,0]),scale:new z().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return gm(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 Cm,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>gm(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 _m(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>gm(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=>gm(this,null,function*(){let i=yield ym(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 km({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 z(e.targetValue[0],e.targetValue[1]),r=new z(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new Mm({material:t,scale:n,offset:r}));return}let n=Tm[r];if(n){c.addBind(new Om({material:t,type:n,targetValue:new W().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};Pm.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 Fm=Pm,Im=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 Wo(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 Ol?[]: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 Ol?[]: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 Yo(e.skeleton.bones,e.skeleton.boneInverses),new U),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 $i;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}};Im.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,Im.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Lm=Im,Rm=new Set([`1.0`,`1.0-beta`]),zm=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return gm(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 gm(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return gm(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(!Rm.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield bm(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 Lm(t,o)})}_v0Import(e,t){return gm(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 bm(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 Lm(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Bm=new V,Vm=new V,Hm=new B,Um=class extends $i{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Nl(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(Bm,Hm,Vm);let n=Bm.set(.1,.1,.1).divide(Vm);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Wm=`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(`.`),Gm={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 Km(e){return e.invert?e.invert():e.inverse(),e}var qm=new V,Jm=new B,Ym=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&&(qm.copy(r.position),Jm.copy(r.quaternion),e[n]={position:qm.toArray(),rotation:Jm.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;qm.set(0,0,0),Jm.identity();let i=this.restPose[n];i?.position&&qm.fromArray(i.position).negate(),i?.rotation&&Km(Jm.fromArray(i.rotation)),qm.add(r.position),Jm.premultiply(r.quaternion),e[n]={position:qm.toArray(),rotation:Jm.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(qm.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Jm.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}},Xm=new V,Zm=new B,Qm=new V,$m=class e extends Ym{static _setupTransforms(e){let t=new Qi;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Wm.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new V,c=new B;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,Xm),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new B;(o=s.parent)==null||o.matrixWorld.decompose(Xm,l,Xm),a[t]=l}});let o={};return Wm.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Gm[a],a!=null);)s=n[a];let c=new Qi;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(){Wm.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Zm.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(Qm);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},eh=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 Ym(e),this._normalizedHumanBones=new $m(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new Ym(e.humanBones),this._normalizedHumanBones=new $m(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()}},th={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`},nh=new Set([`1.0`,`1.0-beta`]),rh={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},ih=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return gm(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return gm(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(!nh.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=>gm(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=rh[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 eh(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Um(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return gm(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=>gm(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=rh[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 eh(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Um(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(th).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},ah=class extends K{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new G(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(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}},oh=class extends K{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new V,this._currentTail=new V,this._attrPos=new G(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(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}},sh=new B,ch=new B,lh=new V,uh=new V,dh=Math.sqrt(2)/2,fh=new B(0,0,-dh,dh),ph=new V(0,1,0),mh=class extends $i{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new ah;e.radius=.5;let t=new bo({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Mo(e,t),this.add(this._meshPitch)}{let e=new ah;e.radius=.5;let t=new bo({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Mo(e,t),this.add(this._meshYaw)}{let e=new oh;e.radius=.1;let t=new ps({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Ts(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=ri.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ri.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(lh),this.vrmLookAt.getLookAtWorldQuaternion(sh),sh.multiply(this.vrmLookAt.getFaceFrontQuaternion(ch)),this._meshYaw.position.copy(lh),this._meshYaw.quaternion.copy(sh),this._meshPitch.position.copy(lh),this._meshPitch.quaternion.copy(sh),this._meshPitch.quaternion.multiply(ch.setFromAxisAngle(ph,t)),this._meshPitch.quaternion.multiply(fh);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(uh).sub(lh),this._lineTarget.geometry.tail.copy(uh),this._lineTarget.geometry.update(),this._lineTarget.position.copy(lh)),super.updateMatrixWorld(e)}},hh=new V,gh=new V;function _h(e,t){return e.matrixWorld.decompose(hh,t,gh),t}function vh(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function yh(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var bh=new V(0,0,1),xh=new V,Sh=new V,Ch=new V,wh=new B,Th=new B,Eh=new B,Dh=new B,Oh=new Fi,kh=class e{constructor(e,t){this.offsetFromHeadBone=new V,this.autoUpdate=!0,this.faceFront=new V(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new B)}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 Fi)}getEuler(e){return e.set(ri.DEG2RAD*this._pitch,ri.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 _h(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(bh)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=vh(this.faceFront);return Oh.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Oh).premultiply(Dh.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(Th),this.getFaceFrontQuaternion(Eh),e.copy(bh).applyQuaternion(Th).applyQuaternion(Eh).applyEuler(this.getEuler(Oh))}lookAt(e){let t=wh.copy(this._restHeadWorldQuaternion).multiply(Km(this.getLookAtWorldQuaternion(Th))),n=this.getLookAtWorldPosition(Sh),r=Ch.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=vh(this.faceFront),[o,s]=vh(r),c=yh(o-i),l=yh(a-s);this._yaw=ri.RAD2DEG*c,this._pitch=ri.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(xh)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};kh.EULER_ORDER=`YXZ`;var Ah=kh,jh=new V(0,0,1),Mh=new B,Nh=new B,Ph=new Fi(0,0,0,`YXZ`),Fh=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 V(0,0,1),this._restQuatLeftEye=new B,this._restQuatRightEye=new B,this._restLeftEyeParentWorldQuat=new B,this._restRightEyeParentWorldQuat=new B;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),_h(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),_h(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?Ph.x=-ri.DEG2RAD*this.rangeMapVerticalDown.map(-t):Ph.x=ri.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Ph.y=-ri.DEG2RAD*this.rangeMapHorizontalInner.map(-e):Ph.y=ri.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Mh.setFromEuler(Ph),this._getWorldFaceFrontQuat(Nh),i.quaternion.copy(Nh).multiply(Mh).multiply(Nh.invert()),Mh.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Mh).premultiply(Mh.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?Ph.x=-ri.DEG2RAD*this.rangeMapVerticalDown.map(-t):Ph.x=ri.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Ph.y=-ri.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):Ph.y=ri.DEG2RAD*this.rangeMapHorizontalInner.map(e),Mh.setFromEuler(Ph),this._getWorldFaceFrontQuat(Nh),a.quaternion.copy(Nh).multiply(Mh).multiply(Nh.invert()),Mh.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Mh).premultiply(Mh.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ri.RAD2DEG*e.y,n=ri.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(jh)<.01)return e.identity();let[t,n]=vh(this.faceFront);return Ph.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Ph)}};Fh.type=`bone`;var Ih=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=ri.RAD2DEG*e.y,n=ri.RAD2DEG*e.x;this.applyYawPitch(t,n)}};Ih.type=`expression`;var Lh=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*Sm(e/this.inputMaxValue)}},Rh=new Set([`1.0`,`1.0-beta`]),zh=.01,Bh=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return gm(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 gm(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 gm(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(!Rh.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 Ih(n,s,c,l,u):new Fh(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<zh&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=zh),new Lh(n,r)}_v0Import(e,t,n){return gm(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 Ih(n,a,o,s,c):new Fh(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 Fh&&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<zh&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=zh),new Lh(r,i)}_importLookAt(e,t){let n=new Ah(e,t);if(this.helperRoot){let e=new mh(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function Vh(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 Hh=new Set([`1.0`,`1.0-beta`]),Uh=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 gm(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return gm(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(!Hh.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 gm(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 gm(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 Fc().loadAsync(Vh(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Wh=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()}},Gh=class extends Wh{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)})}},Kh=Object.defineProperty,qh=Object.getOwnPropertySymbols,Jh=Object.prototype.hasOwnProperty,Yh=Object.prototype.propertyIsEnumerable,Xh=(e,t,n)=>t in e?Kh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zh=(e,t)=>{for(var n in t||={})Jh.call(t,n)&&Xh(e,n,t[n]);if(qh)for(var n of qh(t))Yh.call(t,n)&&Xh(e,n,t[n]);return e},Qh=(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 $h(e,t){e.colorSpace=t}var eg=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 W().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return Qh(this,null,function*(){let r=Qh(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&&$h(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Qh(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},tg=`// #define PHONG
4104
+ }`,Uf=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Rs(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new tc({vertexShader:Vf,fragmentShader:Hf,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Mo(new Gs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Wf=class extends jr{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new Uf,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new z,C=null,w=new Xc;w.viewport=new xi;let T=new Xc;T.viewport=new xi;let E=[w,T],D=new dl,O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new ta,b[e]=t),t.getHandSpace()};function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ee(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,ee),r.removeEventListener(`inputsourceschange`,te);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}O=null,k=null,h.reset();for(let e in g)delete g[e];e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,le.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&I(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&I(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,A),r.addEventListener(`selectstart`,A),r.addEventListener(`selectend`,A),r.addEventListener(`squeeze`,A),r.addEventListener(`squeezestart`,A),r.addEventListener(`squeezeend`,A),r.addEventListener(`end`,ee),r.addEventListener(`inputsourceschange`,te),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?un:ln,a=_.stencil?nn:Zt);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new Ci(d.textureWidth,d.textureHeight,{format:cn,type:Kt,depthTexture:new Is(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ci(f.framebufferWidth,f.framebufferHeight,{format:cn,type:Kt,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),le.setContext(r),le.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function te(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ne=new V,re=new V;function ie(e,t,n){ne.setFromMatrixPosition(t.matrixWorld),re.setFromMatrixPosition(n.matrixWorld);let r=ne.distanceTo(re),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ae(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,(O!==D.near||k!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=e.layers.mask|6,w.layers.mask=D.layers.mask&-5,T.layers.mask=D.layers.mask&-3;let i=e.parent,a=D.cameras;ae(D,i);for(let e=0;e<a.length;e++)ae(a[e],i);a.length===2?ie(D,w,T):D.projectionMatrix.copy(w.projectionMatrix),oe(e,D,i)};function oe(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=Fr*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return D},this.getFoveation=function(){if(!(d===null&&f===null))return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(D)},this.getCameraTexture=function(e){return g[e]};let se=null;function ce(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==D.cameras.length&&(D.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=E[n];o===void 0&&(o=new Xc,o.layers.enable(n),o.viewport=new xi,E[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(D.matrix.copy(o.matrix),D.matrix.decompose(D.position,D.quaternion,D.scale)),i===!0&&D.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new Rs,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}se&&se(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let le=new Il;le.setAnimationLoop(ce),this.setAnimationLoop=function(e){se=e},this.dispose=function(){}}},Gf=new U,Kf=new H;Kf.set(-1,0,0,0,1,0,0,0,1);function qf(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Zs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(Gf.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(Kf),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function Jf(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return L(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):ArrayBuffer.isView(o)?i.__data.set(new o.constructor(o.buffer,o.byteOffset,i.__data.length)):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:ArrayBuffer.isView(i)?r[a]=i.slice():r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?I(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):I(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var Yf=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Xf=null;function Zf(){return Xf===null&&(Xf=new Ko(Yf,16,16,pn,$t),Xf.name=`DFG_LUT`,Xf.minFilter=Ut,Xf.magFilter=Ut,Xf.wrapS=Rt,Xf.wrapT=Rt,Xf.generateMipmaps=!1,Xf.needsUpdate=!0),Xf}var Qf=class{constructor(e={}){let{canvas:t=Cr(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Kt}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([hn,mn,fn]),g=new Set([Kt,Zt,Yt,nn,en,tn]),_=new Uint32Array(4),v=new Int32Array(4),y=new V,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null;this._outputColorSpace=fr;let O=0,k=0,A=null,ee=-1,te=null,ne=new xi,re=new xi,ie=null,ae=new W(0),oe=0,se=t.width,ce=t.height,le=1,ue=null,de=null,j=new xi(0,0,se,ce),fe=new xi(0,0,se,ce),pe=!1,M=new fs,me=!1,he=!1,ge=new U,_e=new V,ve=new xi,ye={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},be=!1;function xe(){return A===null?le:1}let N=n;function Se(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r184`),t.addEventListener(`webglcontextlost`,Ke,!1),t.addEventListener(`webglcontextrestored`,qe,!1),t.addEventListener(`webglcontextcreationerror`,Je,!1),N===null){let t=`webgl2`;if(N=Se(t,e),N===null)throw Se(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw L(`WebGLRenderer: `+e.message),e}let Ce,we,P,Te,F,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue;function We(){Ce=new hu(N),Ce.init(),Ve=new Bf(N,Ce),we=new Gl(N,Ce,e,Ve),P=new Rf(N,Ce),we.reversedDepthBuffer&&d&&P.buffers.depth.setReversed(!0),Te=new vu(N),F=new vf,Ee=new zf(N,Ce,P,F,we,Ve,Te),De=new mu(T),Oe=new Ll(N),He=new Ul(N,Oe),ke=new gu(N,Oe,Te,He),Ae=new bu(N,ke,Oe,He,Te),Re=new yu(N,we,Ee),Fe=new Kl(F),je=new _f(T,De,Ce,we,He,Fe),Me=new qf(T,F),Ne=new Sf,Pe=new kf(Ce),Le=new Hl(T,De,P,Ae,p,s),Ie=new Lf(T,Ae,we),Ue=new Jf(N,Te,we,P),ze=new Wl(N,Ce,Te),Be=new _u(N,Ce,Te),Te.programs=je.programs,T.capabilities=we,T.extensions=Ce,T.properties=F,T.renderLists=Ne,T.shadowMap=Ie,T.state=P,T.info=Te}We(),m!==1009&&(w=new Su(m,t.width,t.height,r,i));let Ge=new Wf(T,N);this.xr=Ge,this.getContext=function(){return N},this.getContextAttributes=function(){return N.getContextAttributes()},this.forceContextLoss=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Ce.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(e){e!==void 0&&(le=e,this.setSize(se,ce,!1))},this.getSize=function(e){return e.set(se,ce)},this.setSize=function(e,n,r=!0){if(Ge.isPresenting){I(`WebGLRenderer: Can't change size while VR device is presenting.`);return}se=e,ce=n,t.width=Math.floor(e*le),t.height=Math.floor(n*le),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(se*le,ce*le).floor()},this.setDrawingBufferSize=function(e,n,r){se=e,ce=n,le=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){L(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){I(`THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(ne)},this.getViewport=function(e){return e.copy(j)},this.setViewport=function(e,t,n,r){e.isVector4?j.set(e.x,e.y,e.z,e.w):j.set(e,t,n,r),P.viewport(ne.copy(j).multiplyScalar(le).round())},this.getScissor=function(e){return e.copy(fe)},this.setScissor=function(e,t,n,r){e.isVector4?fe.set(e.x,e.y,e.z,e.w):fe.set(e,t,n,r),P.scissor(re.copy(fe).multiplyScalar(le).round())},this.getScissorTest=function(){return pe},this.setScissorTest=function(e){P.setScissorTest(pe=e)},this.setOpaqueSort=function(e){ue=e},this.setTransparentSort=function(e){de=e},this.getClearColor=function(e){return e.copy(Le.getClearColor())},this.setClearColor=function(){Le.setClearColor(...arguments)},this.getClearAlpha=function(){return Le.getClearAlpha()},this.setClearAlpha=function(){Le.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(A!==null){let t=A.texture.format;e=h.has(t)}if(e){let e=A.texture.type,t=g.has(e),n=Le.getClearColor(),r=Le.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,N.clearBufferuiv(N.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,N.clearBufferiv(N.COLOR,0,v))}else r|=N.COLOR_BUFFER_BIT}t&&(r|=N.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=N.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&N.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,Ke,!1),t.removeEventListener(`webglcontextrestored`,qe,!1),t.removeEventListener(`webglcontextcreationerror`,Je,!1),Le.dispose(),Ne.dispose(),Pe.dispose(),F.dispose(),De.dispose(),Ae.dispose(),He.dispose(),Ue.dispose(),je.dispose(),Ge.dispose(),Ge.removeEventListener(`sessionstart`,tt),Ge.removeEventListener(`sessionend`,nt),rt.stop()};function Ke(e){e.preventDefault(),Er(`WebGLRenderer: Context Lost.`),E=!0}function qe(){Er(`WebGLRenderer: Context Restored.`),E=!1;let e=Te.autoReset,t=Ie.enabled,n=Ie.autoUpdate,r=Ie.needsUpdate,i=Ie.type;We(),Te.autoReset=e,Ie.enabled=t,Ie.autoUpdate=n,Ie.needsUpdate=r,Ie.type=i}function Je(e){L(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Ye(e){let t=e.target;t.removeEventListener(`dispose`,Ye),Xe(t)}function Xe(e){Ze(e),F.remove(e)}function Ze(e){let t=F.get(e).programs;t!==void 0&&(t.forEach(function(e){je.releaseProgram(e)}),e.isShaderMaterial&&je.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ye);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=pt(e,t,n,r,i);P.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=ke.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;He.setup(i,r,s,n,c);let h,g=ze;if(c!==null&&(h=Oe.get(c),g=Be,g.setIndex(h)),i.isMesh)r.wireframe===!0?(P.setLineWidth(r.wireframeLinewidth*xe()),g.setMode(N.LINES)):g.setMode(N.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),P.setLineWidth(e*xe()),i.isLineSegments?g.setMode(N.LINES):i.isLineLoop?g.setMode(N.LINE_LOOP):g.setMode(N.LINE_STRIP)}else i.isPoints?g.setMode(N.POINTS):i.isSprite&&g.setMode(N.TRIANGLES);if(i.isBatchedMesh)if(Ce.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Oe.get(c).bytesPerElement:1,o=F.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(N,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Qe(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,lt(e,t,n),e.side=0,e.needsUpdate=!0,lt(e,t,n),e.side=2):lt(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),x=Pe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Qe(a,n,e),r.add(a)}else Qe(t,n,e),r.add(t)}),x=C.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){F.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Ce.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let $e=null;function et(e){$e&&$e(e)}function tt(){rt.stop()}function nt(){rt.start()}let rt=new Il;rt.setAnimationLoop(et),typeof self<`u`&&rt.setContext(self),this.setAnimationLoop=function(e){$e=e,Ge.setAnimationLoop(e),e===null?rt.stop():rt.start()},Ge.addEventListener(`sessionstart`,tt),Ge.addEventListener(`sessionend`,nt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){L(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=Ge.enabled===!0&&Ge.isPresenting===!0,r=w!==null&&(A===null||n)&&w.begin(T,A);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ge.enabled===!0&&Ge.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(Ge.cameraAutoUpdate===!0&&Ge.updateCamera(t),t=Ge.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,A),x=Pe.get(e,C.length),x.init(t),x.state.textureUnits=Ee.getTextureUnits(),C.push(x),ge.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),M.setFromProjectionMatrix(ge,yr,t.reversedDepth),he=this.localClippingEnabled,me=Fe.init(this.clippingPlanes,he),b=Ne.get(e,S.length),b.init(),S.push(b),Ge.enabled===!0&&Ge.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&it(e,t,-1/0,T.sortObjects)}it(e,t,0,T.sortObjects),b.finish(),T.sortObjects===!0&&b.sort(ue,de),be=Ge.enabled===!1||Ge.isPresenting===!1||Ge.hasDepthSensing()===!1,be&&Le.addToRenderList(b,e),this.info.render.frame++,me===!0&&Fe.beginShadows();let i=x.state.shadowsArray;if(Ie.render(i,e,t),me===!0&&Fe.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];ot(n,r,e,a)}be&&Le.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];at(b,e,n,n.viewport)}}else r.length>0&&ot(n,r,e,t),be&&Le.render(e),at(b,e,t)}A!==null&&k===0&&(Ee.updateMultisampleRenderTarget(A),Ee.updateRenderTargetMipmap(A)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),He.resetDefaultState(),ee=-1,te=null,C.pop(),C.length>0?(x=C[C.length-1],Ee.setTextureUnits(x.state.textureUnits),me===!0&&Fe.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function it(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||M.intersectsSprite(e)){r&&ve.setFromMatrixPosition(e.matrixWorld).applyMatrix4(ge);let t=Ae.update(e),i=e.material;i.visible&&b.push(e,t,i,n,ve.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||M.intersectsObject(e))){let t=Ae.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),ve.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),ve.copy(e.boundingSphere.center)),ve.applyMatrix4(e.matrixWorld).applyMatrix4(ge)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&b.push(e,t,s,n,ve.z,o)}}else i.visible&&b.push(e,t,i,n,ve.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)it(i[e],t,n,r)}function at(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),me===!0&&Fe.setGlobalState(T.clippingPlanes,n),r&&P.viewport(ne.copy(r)),i.length>0&&st(i,t,n),a.length>0&&st(a,t,n),o.length>0&&st(o,t,n),P.buffers.depth.setTest(!0),P.buffers.depth.setMask(!0),P.buffers.color.setMask(!0),P.setPolygonOffset(!1)}function ot(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Ce.has(`EXT_color_buffer_half_float`)||Ce.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new Ci(1,1,{generateMipmaps:!0,type:e?$t:Kt,minFilter:Gt,samples:Math.max(4,we.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ui.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||ne;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(ae),oe=T.getClearAlpha(),oe<1&&T.setClearColor(16777215,.5),T.clear(),be&&Le.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),me===!0&&Fe.setGlobalState(T.clippingPlanes,r),st(e,n,r),Ee.updateMultisampleRenderTarget(a),Ee.updateRenderTargetMipmap(a),Ce.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,ct(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(Ee.updateMultisampleRenderTarget(a),Ee.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(ae,oe),d!==void 0&&(r.viewport=d),T.toneMapping=u}function st(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&ct(o,t,n,s,l,c)}}function ct(e,t,n,r,i,a){e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function lt(e,t,n){t.isScene!==!0&&(t=ye);let r=F.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=je.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=je.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=De.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Ye),l=new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return dt(e,s),d}else s.uniforms=je.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=je.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=Fe.uniform),dt(e,s),r.needsLights=ht(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function ut(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=kd.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function dt(e,t){let n=F.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function ft(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function pt(e,t,n,r,i){t.isScene!==!0&&(t=ye),Ee.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=A===null?T.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:ui.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=De.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=F.get(r),y=x.state.lights;if(me===!0&&(he===!0||e!==te)){let t=e===te&&r.id===ee;Fe.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Fe.numPlanes||v.numIntersection!==Fe.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=lt(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(P.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==ee&&(ee=r.id,w=!0),v.needsLights){let e=ft(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||te!==e){P.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(N,`projectionMatrix`,e.projectionMatrix),O.setValue(N,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(N,_e.setFromMatrixPosition(e.matrixWorld)),we.logarithmicDepthBuffer&&O.setValue(N,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(N,`isOrthographic`,e.isOrthographicCamera===!0),te!==e&&(te=e,w=!0,E=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&O.setValue(N,`directionalShadowMap`,y.state.directionalShadowMap,Ee),y.state.spotShadowMap.length>0&&O.setValue(N,`spotShadowMap`,y.state.spotShadowMap,Ee),y.state.pointShadowMap.length>0&&O.setValue(N,`pointShadowMap`,y.state.pointShadowMap,Ee)),i.isSkinnedMesh){O.setOptional(N,i,`bindMatrix`),O.setOptional(N,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(N,`boneTexture`,e.boneTexture,Ee))}i.isBatchedMesh&&(O.setOptional(N,i,`batchingTexture`),O.setValue(N,`batchingTexture`,i._matricesTexture,Ee),O.setOptional(N,i,`batchingIdTexture`),O.setValue(N,`batchingIdTexture`,i._indirectTexture,Ee),O.setOptional(N,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(N,`batchingColorTexture`,i._colorsTexture,Ee));let ne=n.morphAttributes;if((ne.position!==void 0||ne.normal!==void 0||ne.color!==void 0)&&Re.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(N,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=Zf()),w){if(O.setValue(N,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&mt(k,E),a&&r.fog===!0&&Me.refreshFogUniforms(k,a),Me.refreshMaterialUniforms(k,r,le,ce,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}kd.upload(N,ut(v),k,Ee)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(kd.upload(N,ut(v),k,Ee),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(N,`center`,i.center),O.setValue(N,`modelViewMatrix`,i.modelViewMatrix),O.setValue(N,`normalMatrix`,i.normalMatrix),O.setValue(N,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ue.update(n,S),Ue.bind(n,S)}}return S}function mt(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function ht(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return O},this.getActiveMipmapLevel=function(){return k},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(e,t,n){let r=F.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),F.get(e.texture).__webglTexture=t,F.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=F.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let gt=N.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){A=e,O=t,k=n;let r=null,i=!1,a=!1;if(e){let o=F.get(e);if(o.__useDefaultFramebuffer!==void 0){P.bindFramebuffer(N.FRAMEBUFFER,o.__webglFramebuffer),ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest,P.viewport(ne),P.scissor(re),P.setScissorTest(ie),ee=-1;return}else if(o.__webglFramebuffer===void 0)Ee.setupRenderTarget(e);else if(o.__hasExternalTextures)Ee.rebindTextures(e,F.get(e.texture).__webglTexture,F.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&F.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);Ee.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=F.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&Ee.useMultisampledRTT(e)===!1?F.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,ne.copy(e.viewport),re.copy(e.scissor),ie=e.scissorTest}else ne.copy(j).multiplyScalar(le).floor(),re.copy(fe).multiplyScalar(le).floor(),ie=pe;if(n!==0&&(r=gt),P.bindFramebuffer(N.FRAMEBUFFER,r)&&P.drawBuffers(e,r),P.viewport(ne),P.scissor(re),P.setScissorTest(ie),i){let r=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=F.get(e.textures[t]);N.framebufferTextureLayer(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=F.get(e.texture);N.framebufferTexture2D(N.FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,t.__webglTexture,n)}ee=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){P.bindFramebuffer(N.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(c)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!we.textureTypeReadable(l)){L(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&N.readPixels(t,n,r,i,Ve.convert(c),Ve.convert(l),a)}finally{let e=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=F.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){P.bindFramebuffer(N.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&N.readBuffer(N.COLOR_ATTACHMENT0+s),!we.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!we.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=N.createBuffer();N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.bufferData(N.PIXEL_PACK_BUFFER,a.byteLength,N.STREAM_READ),N.readPixels(t,n,r,i,Ve.convert(l),Ve.convert(u),0);let f=A===null?null:F.get(A).__webglFramebuffer;P.bindFramebuffer(N.FRAMEBUFFER,f);let p=N.fenceSync(N.SYNC_GPU_COMMANDS_COMPLETE,0);return N.flush(),await kr(N,p,4),N.bindBuffer(N.PIXEL_PACK_BUFFER,d),N.getBufferSubData(N.PIXEL_PACK_BUFFER,0,a),N.deleteBuffer(d),N.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;Ee.setTexture2D(e,0),N.copyTexSubImage2D(N.TEXTURE_2D,n,0,0,o,s,i,a),P.unbindTexture()};let _t=N.createFramebuffer(),vt=N.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Ve.convert(t.format),_=Ve.convert(t.type),v;t.isData3DTexture?(Ee.setTexture3D(t,0),v=N.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(Ee.setTexture2DArray(t,0),v=N.TEXTURE_2D_ARRAY):(Ee.setTexture2D(t,0),v=N.TEXTURE_2D),P.activeTexture(N.TEXTURE0),P.pixelStorei(N.UNPACK_FLIP_Y_WEBGL,t.flipY),P.pixelStorei(N.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),P.pixelStorei(N.UNPACK_ALIGNMENT,t.unpackAlignment);let y=P.getParameter(N.UNPACK_ROW_LENGTH),b=P.getParameter(N.UNPACK_IMAGE_HEIGHT),x=P.getParameter(N.UNPACK_SKIP_PIXELS),S=P.getParameter(N.UNPACK_SKIP_ROWS),C=P.getParameter(N.UNPACK_SKIP_IMAGES);P.pixelStorei(N.UNPACK_ROW_LENGTH,h.width),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,h.height),P.pixelStorei(N.UNPACK_SKIP_PIXELS,l),P.pixelStorei(N.UNPACK_SKIP_ROWS,u),P.pixelStorei(N.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=F.get(e),r=F.get(t),h=F.get(n.__renderTarget),g=F.get(r.__renderTarget);P.bindFramebuffer(N.READ_FRAMEBUFFER,h.__webglFramebuffer),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(e).__webglTexture,i,d+n),N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,F.get(t).__webglTexture,a,m+n)),N.blitFramebuffer(l,u,o,s,f,p,o,s,N.DEPTH_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||F.has(e)){let n=F.get(e),r=F.get(t);P.bindFramebuffer(N.READ_FRAMEBUFFER,_t),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,vt);for(let e=0;e<c;e++)w?N.framebufferTextureLayer(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):N.framebufferTexture2D(N.READ_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,n.__webglTexture,i),T?N.framebufferTextureLayer(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):N.framebufferTexture2D(N.DRAW_FRAMEBUFFER,N.COLOR_ATTACHMENT0,N.TEXTURE_2D,r.__webglTexture,a),i===0?T?N.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):N.copyTexSubImage2D(v,a,f,p,l,u,o,s):N.blitFramebuffer(l,u,o,s,f,p,o,s,N.COLOR_BUFFER_BIT,N.NEAREST);P.bindFramebuffer(N.READ_FRAMEBUFFER,null),P.bindFramebuffer(N.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?N.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):N.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?N.compressedTexSubImage2D(N.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):N.texSubImage2D(N.TEXTURE_2D,a,f,p,o,s,g,_,h);P.pixelStorei(N.UNPACK_ROW_LENGTH,y),P.pixelStorei(N.UNPACK_IMAGE_HEIGHT,b),P.pixelStorei(N.UNPACK_SKIP_PIXELS,x),P.pixelStorei(N.UNPACK_SKIP_ROWS,S),P.pixelStorei(N.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&N.generateMipmap(v),P.unbindTexture()},this.initRenderTarget=function(e){F.get(e).__webglFramebuffer===void 0&&Ee.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?Ee.setTextureCube(e,0):e.isData3DTexture?Ee.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?Ee.setTexture2DArray(e,0):Ee.setTexture2D(e,0),P.unbindTexture()},this.resetState=function(){O=0,k=0,A=null,P.reset(),He.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return yr}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=ui._getDrawingBufferColorSpace(e),t.unpackColorSpace=ui._getUnpackColorSpace()}},$f=class{entries=new Map;loader;constructor(e){this.loader=e??((e,t)=>new Lc().load(e,()=>t?.onLoad?.(),void 0,e=>t?.onError?.(e)))}load(e){for(let[t,n]of Object.entries(e)){let e=n.type;if(e!==`texture`&&e!==`spritesheet`)throw new y(`BAD_FORMAT`,`Asset '${t}': "type" must be 'texture' or 'spritesheet', got ${JSON.stringify(e)}.`);if(typeof n.url!=`string`||n.url===``)throw new y(`BAD_FORMAT`,`Asset '${t}': "url" must be a non-empty string.`);let r,i;if(e===`spritesheet`){if(typeof n.frameWidth!=`number`||typeof n.frameHeight!=`number`)throw new y(`BAD_FORMAT`,`Asset '${t}': spritesheets need numeric "frameWidth" and "frameHeight".`);r=n.frameWidth,i=n.frameHeight}let a=this.entries.get(t),o={status:`loading`},s=this.loader(n.url,{onLoad:()=>{o.status=`ready`},onError:e=>{o.status=`error`,console.error(`[incanto] failed to load texture '${t}' (${n.url}):`,e)}});a&&a.texture!==s&&a.texture.dispose(),s.colorSpace=fr,n.filter===`nearest`?(s.magFilter=Bt,s.minFilter=Bt,s.generateMipmaps=!1):s.magFilter=Ut,s.needsUpdate=!0,this.entries.set(t,{texture:s,type:e,frameWidth:r,frameHeight:i,state:o})}}status(e){return this.entries.get(e)?.state.status}getTexture(e){return this.resolve(e).texture}getSheet(e){let t=this.resolve(e);if(t.type!==`spritesheet`)throw new y(`BAD_FORMAT`,`Asset '${e}' is a plain texture; a spritesheet (with frameWidth/frameHeight) is required here.`);return{texture:t.texture,frameWidth:t.frameWidth,frameHeight:t.frameHeight}}resolve(e){if(!e.startsWith(`$`))throw new y(`UNKNOWN_ASSET`,`Asset reference '${e}' must use the '$key' form (e.g. '$${e}').`);let t=this.entries.get(e.slice(1));if(!t)throw new y(`UNKNOWN_ASSET`,`Unknown asset '${e}'. Declared assets: [${[...this.entries.keys()].join(`, `)}].`);return t}};function ep(e,t){let n=e.shape;if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new y(`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 y(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new y(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var tp=class extends Fe{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 rt(this.orderGroup,this.renderOrder)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new Qi}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-ri.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}},np=class extends tp{static props={collider:{default:{}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){ep(e.collider,e.name)}_physics=null},rp=class extends np{static typeName=`StaticBody2D`},ip=class extends np{static typeName=`Area2D`},ap=class extends np{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]},op=class extends np{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 y(`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)}isOnFloor(){return this._grounded}},sp=new Set;function cp(e){return sp.add(e),()=>sp.delete(e)}function lp(e){return[...sp].filter(t=>t.dimension===e)}var up=class extends tp{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`rope`,`spring`]},target:{default:``},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 np))throw new y(`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 y(`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 np))throw new y(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},dp=`modulepreload`,fp=function(e,t){return new URL(e,t).href},pp={},mp=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=fp(t,n),t in pp)return;pp[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:dp,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Y=100,hp=Math.PI/180;async function gp(e,t){let n=await mp(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await n.init(),new _p(n,e,t)}var _p=class{R;engine;debugDraw=!1;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.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Y,y:(i[1]??0)/Y}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=cp(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}step(e){if(this.lastDt=e,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)/Y,y:(e[1]??0)/Y}}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]=wp(e);e.position=[n.x*Y-t,n.y*Y-r]}if(e instanceof ap){e.fixedRotation||(e.rotation=t.body.rotation()/hp);let n=t.body.linvel();e.linearVelocity=[n.x*Y,n.y*Y],t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0}let[r,i]=Cp(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`;r.emit(a,i),i.emit(a,r)})}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*hp);let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=Cp(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)/Y*1,y:(n*this.lastDt+i)/Y*1},o=t.body.translation().y*Y+xp(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>Sp(r)+bp))});let s=this.kcc.computedMovement(),c=t.body.translation();if(t.body.setNextKinematicTranslation({x:c.x+s.x,y:c.y+s.y}),e._grounded=this.kcc.computedGrounded(),e._grounded){let n=(c.x+s.x)*Y,r=(c.y+s.y)*Y+xp(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&!(i.node instanceof op)){t.ground=i.node;let[e,n]=Cp(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.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Y;return 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)/Y,y:(e.anchor[1]??0)/Y},s={x:(e.targetAnchor[0]??0)/Y,y:(e.targetAnchor[1]??0)/Y},c=e.length/Y;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]/Y,y:e[1]/Y},{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/Y,!0,c,void 0,s,void 0,e=>!e.isSensor());return l?{distance:l.timeOfImpact*Y,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;syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=t!==this.lastStructure||e.root!==this.lastRoot;n&&(this.lastStructure=t,this.lastRoot=e.root,this.bodySet.clear(),yp(e.root,this.bodySet)),n&&(this.jointSet.clear(),vp(e.root,this.jointSet));let r=this.bodySet;for(let e of r){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),console.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(n),n)for(let[e,t]of this.entries)r.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]=Cp(e),a=r/Y,o=i/Y,s;s=e instanceof ap?n.RigidBodyDesc.dynamic():e instanceof op||e instanceof ip?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),s.setTranslation(a,o).setRotation(e.rotation*hp),e instanceof ap&&(s.setGravityScale(e.gravityScale),s.setLinvel((e.linearVelocity[0]??0)/Y,(e.linearVelocity[1]??0)/Y),e.fixedRotation&&s.lockRotations());let c=this.world.createRigidBody(s),l=Tp(n,e.collider,e.name);l.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof ip&&l.setSensor(!0),e instanceof ap&&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]=Cp(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Y,y:i/Y},!0),t.lastX=r,t.lastY=i),e instanceof ap){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Y,y:r/Y},!0),t.lastVX=n,t.lastVY=r)}return t}};function vp(e,t){e instanceof up&&t.add(e);for(let n of e.children)vp(n,t)}function yp(e,t){e instanceof np&&t.add(e);for(let n of e.children)yp(n,t)}var bp=4;function xp(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 Sp(e){let[,t]=Cp(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 Cp(e){let t=0,n=0;for(let r=e;r;r=r.parent)r instanceof tp&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function wp(e){let t=0,n=0;for(let r=e.parent;r;r=r.parent)r instanceof tp&&(t+=r.position[0]??0,n+=r.position[1]??0);return[t,n]}function Tp(e,t,n){ep(t,n);let r=Ep(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Y,(i[1]??0)/Y),r}function Ep(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 y(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Y,r[1]/2/Y)}if(r===`circle`){if(typeof t.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Y)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Y,t.radius/Y)}throw new y(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}var Dp=new Gs(1,1),Op=class extends tp{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 Mo(Dp,new bo({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}},kp=class extends Op{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 y(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=Ap(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 Ap(e,t){if(!Array.isArray(e)||e.length===0)throw new y(`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 jp=class extends tp{static typeName=`Camera2D`;static props={follow:{default:``},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 tp))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 y(`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=Mp(n,i+c,o-c),r=Mp(r,a+l,s-l)}return{x:n,y:r}}};function Mp(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var Np=class extends Fe{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`}};mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;onReady(){if(!(this.parent instanceof op))throw new y(`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 y(`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 op))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;if(n.velocity[0]=i.x*this.maxSpeed,n.isOnFloor()){let e=r.justPressed(this.jumpAction);n.velocity[1]=e?-Math.sqrt(2*a*this.jumpHeight):20}else n.velocity[1]=(n.velocity[1]??0)+a*e;n.moveAndSlide()}},Pp=new Gs(1,1),Fp=class extends tp{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 Mo(Pp,new bo({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}},Ip=new Gs(1,1),Lp=class extends tp{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 Mo(Ip,new bo({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 Fs(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)}},Rp=new Gs(1,1),zp=class e extends tp{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`,...at]},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`&&!at.includes(t.preset))throw new y(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${at.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:at});if(t.blend!==`add`&&t.blend!==`normal`)throw new y(`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){ot(this,this.preset,ge(e.typeName));let t=this.tree?.engine?.rng??new b(4660);this.sim=new ct({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 W,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 bo({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new is(Rp,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(vr),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let n=this.mesh,r=this.refreshPalette(),i=r?null:Vp.set(this.colorStart),a=Hp.set(this.colorEnd),o=this.shimmer,s=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Bp.makeScale(t,t,1),Bp.setPosition(e.x,-e.y,0),n.setMatrixAt(s,Bp);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))),Up.copy(c).lerp(a,e.t).multiplyScalar(l),n.setColorAt(s,Up),s+=1}),n.count=s,n.instanceMatrix.needsUpdate=!0,n.instanceColor&&(n.instanceColor.needsUpdate=!0),n.renderOrder=this.effectiveRenderOrder}},Bp=new U,Vp=new W,Hp=new W,Up=new W;function Wp(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 y(`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 Gp(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 Kp=class extends tp{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;Wp(t._cells,t._legend)}grid(){return Wp(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;Gp(this.grid(),new Set(this._solid)).forEach((t,n)=>{let r=new rp(`__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 Mo(new K,new bo({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=Bt,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 G(new Float32Array(a),3)),e.setAttribute(`uv`,new G(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()}},qp=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],Jp=class extends Fe{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:qp}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new $i,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!qp.includes(t))throw new y(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${qp.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:qp})}_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 Yp(){lt(),M(tp),M(Op),M(Fp),M(zp),M(kp),M(jp),M(Lp),M(Jp),M(rp),M(ap),M(ip),M(op),M(Np),M(up),M(Kp)}function Xp(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function Zp(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}var Qp=new Ca,$p=new V,em=12,tm=new Float32Array(16);function nm(e){if(!(e instanceof tp))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),Qp.setFromObject(t),Qp.getSize($p);let n,r,i,a;if(!Number.isFinite($p.x)||$p.x===0&&$p.y===0){let e=new V().setFromMatrixPosition(t.matrixWorld);n=e.x-em,i=e.x+em,r=e.y-em,a=e.y+em}else n=Qp.min.x-2,i=Qp.max.x+2,r=Qp.min.y-2,a=Qp.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return tm.set(o),tm}function rm(){return{visited:new Set,cameras:[]}}function im(e,t,n,r,i,a,o){let s=a??rm();s.visited.clear(),s.cameras.length=0,am(e,t,n,!1,s.visited,s.cameras,r,i,o?.ignoreStatic===!0),om(t,s.visited),om(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 am(e,t,n,r,i,a,o,s,c){let l=t,u=r;if(e instanceof tp&&!(e instanceof Jp)){let t=e._ensureObject2D();if(e.static&&!c&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof Jp){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 tp){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(o),i.add(n),e instanceof jp&&!r&&a.push(e),l=n}for(let t of e.children)am(t,l,n,u,i,a,o,s,c);if(e instanceof tp&&!(e instanceof Jp)){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 om(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&&om(i,t)}}var sm=class{viewOverride=null;webgl;worldScene=new ca;syncScratch=rm();ignoreStatic=!1;uiScene=new ca;worldCam=new tl(-1,1,1,-1,-1e3,1e3);uiCam=new tl(-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 $f;let t=ut(e.engine.scene?.environment,{antialias:!0,pixelRatio:1},globalThis.devicePixelRatio??1,e);this.webgl=new Qf({canvas:e.canvas,antialias:t.antialias}),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new Ts(new K,new ps({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 Ts(new K,new ps({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?nm(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 G(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of lp(`2d`))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 G(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 W(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(lm);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:_t(e.viewport),o=a?vt(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r,{activeCamera:l}=im(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)),cm(this.worldCam,u.x,u.y,s/d,c/d),cm(this.uiCam,s/2,c/2,s,c),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 Zp(this.lastView,e,t)}screenFromWorld(e,t){return Xp(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;dm.set((e-i)/o*2-1,-((t-a)/s*2-1)),fm.setFromCamera(dm,this.worldCam);let c=fm.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||(pm.makeEmpty(),pm.expandByObject(t),pm.isEmpty())||(pm.getSize(um),um.x===0&&um.y===0))return null;let n=this.screenFromWorld(pm.min.x,-pm.max.y),r=this.screenFromWorld(pm.max.x,-pm.min.y);return{x:n.x,y:n.y,w:r.x-n.x,h:r.y-n.y}}dispose(){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 cm(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 lm=new z,um=new V,dm=new z,fm=new Al,pm=new Ca,mm=e({enablePhysics2D:()=>gp}),hm=(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())}),gm=(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())}),_m=class extends Qi{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 vm(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 ym(e,t){return gm(this,null,function*(){return vm(e,t,yield e.parser.getDependency(`node`,t))})}function bm(e){return gm(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=vm(e,r,t);i!=null&&n.set(r,i)}),n})}var xm={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 Sm(e){return Math.max(Math.min(e,1),0)}var Cm=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(xm));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(xm));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=Sm(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}}},wm={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},Tm={_Color:wm.Color,_EmissionColor:wm.EmissionColor,_ShadeColor:wm.ShadeColor,_RimColor:wm.RimColor,_OutlineColor:wm.OutlineColor},Em=new W,Dm=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(Em.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 W(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}};Dm._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 Om=Dm,km=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)})}},Am=new z,jm=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(Am.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(Am.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))})}};jm._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var Mm=jm,Nm=new Set([`1.0`,`1.0-beta`]),Pm=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return gm(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return gm(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(!Nm.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(xm)),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 Cm;return yield Promise.all(Array.from(o.entries()).map(t=>gm(this,[t],function*([t,n]){var r,i,a;let o=new _m(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=>gm(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield ym(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 km({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=>gm(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Om({material:t,type:e.type,targetValue:new W().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>gm(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new Mm({material:t,offset:new z().fromArray(e.offset??[0,0]),scale:new z().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return gm(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 Cm,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>gm(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 _m(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>gm(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=>gm(this,null,function*(){let i=yield ym(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 km({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 z(e.targetValue[0],e.targetValue[1]),r=new z(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new Mm({material:t,scale:n,offset:r}));return}let n=Tm[r];if(n){c.addBind(new Om({material:t,type:n,targetValue:new W().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};Pm.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 Fm=Pm,Im=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 Wo(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 Ol?[]: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 Ol?[]: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 Yo(e.skeleton.bones,e.skeleton.boneInverses),new U),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 $i;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}};Im.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,Im.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var Lm=Im,Rm=new Set([`1.0`,`1.0-beta`]),zm=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return gm(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 gm(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return gm(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(!Rm.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield bm(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 Lm(t,o)})}_v0Import(e,t){return gm(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 bm(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 Lm(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},Bm=new V,Vm=new V,Hm=new B,Um=class extends $i{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Nl(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(Bm,Hm,Vm);let n=Bm.set(.1,.1,.1).divide(Vm);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},Wm=`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(`.`),Gm={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 Km(e){return e.invert?e.invert():e.inverse(),e}var qm=new V,Jm=new B,Ym=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&&(qm.copy(r.position),Jm.copy(r.quaternion),e[n]={position:qm.toArray(),rotation:Jm.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;qm.set(0,0,0),Jm.identity();let i=this.restPose[n];i?.position&&qm.fromArray(i.position).negate(),i?.rotation&&Km(Jm.fromArray(i.rotation)),qm.add(r.position),Jm.premultiply(r.quaternion),e[n]={position:qm.toArray(),rotation:Jm.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(qm.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(Jm.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}},Xm=new V,Zm=new B,Qm=new V,$m=class e extends Ym{static _setupTransforms(e){let t=new Qi;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};Wm.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new V,c=new B;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,Xm),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new B;(o=s.parent)==null||o.matrixWorld.decompose(Xm,l,Xm),a[t]=l}});let o={};return Wm.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=Gm[a],a!=null);)s=n[a];let c=new Qi;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(){Wm.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=Zm.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(Qm);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},eh=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 Ym(e),this._normalizedHumanBones=new $m(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new Ym(e.humanBones),this._normalizedHumanBones=new $m(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()}},th={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`},nh=new Set([`1.0`,`1.0-beta`]),rh={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},ih=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return gm(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return gm(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(!nh.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=>gm(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=rh[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 eh(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new Um(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return gm(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=>gm(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=rh[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 eh(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new Um(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(th).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},ah=class extends K{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new G(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(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}},oh=class extends K{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new V,this._currentTail=new V,this._attrPos=new G(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(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}},sh=new B,ch=new B,lh=new V,uh=new V,dh=Math.sqrt(2)/2,fh=new B(0,0,-dh,dh),ph=new V(0,1,0),mh=class extends $i{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new ah;e.radius=.5;let t=new bo({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Mo(e,t),this.add(this._meshPitch)}{let e=new ah;e.radius=.5;let t=new bo({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Mo(e,t),this.add(this._meshYaw)}{let e=new oh;e.radius=.1;let t=new ps({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new Ts(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=ri.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=ri.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(lh),this.vrmLookAt.getLookAtWorldQuaternion(sh),sh.multiply(this.vrmLookAt.getFaceFrontQuaternion(ch)),this._meshYaw.position.copy(lh),this._meshYaw.quaternion.copy(sh),this._meshPitch.position.copy(lh),this._meshPitch.quaternion.copy(sh),this._meshPitch.quaternion.multiply(ch.setFromAxisAngle(ph,t)),this._meshPitch.quaternion.multiply(fh);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(uh).sub(lh),this._lineTarget.geometry.tail.copy(uh),this._lineTarget.geometry.update(),this._lineTarget.position.copy(lh)),super.updateMatrixWorld(e)}},hh=new V,gh=new V;function _h(e,t){return e.matrixWorld.decompose(hh,t,gh),t}function vh(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function yh(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var bh=new V(0,0,1),xh=new V,Sh=new V,Ch=new V,wh=new B,Th=new B,Eh=new B,Dh=new B,Oh=new Fi,kh=class e{constructor(e,t){this.offsetFromHeadBone=new V,this.autoUpdate=!0,this.faceFront=new V(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new B)}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 Fi)}getEuler(e){return e.set(ri.DEG2RAD*this._pitch,ri.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 _h(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(bh)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=vh(this.faceFront);return Oh.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Oh).premultiply(Dh.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(Th),this.getFaceFrontQuaternion(Eh),e.copy(bh).applyQuaternion(Th).applyQuaternion(Eh).applyEuler(this.getEuler(Oh))}lookAt(e){let t=wh.copy(this._restHeadWorldQuaternion).multiply(Km(this.getLookAtWorldQuaternion(Th))),n=this.getLookAtWorldPosition(Sh),r=Ch.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=vh(this.faceFront),[o,s]=vh(r),c=yh(o-i),l=yh(a-s);this._yaw=ri.RAD2DEG*c,this._pitch=ri.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(xh)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};kh.EULER_ORDER=`YXZ`;var Ah=kh,jh=new V(0,0,1),Mh=new B,Nh=new B,Ph=new Fi(0,0,0,`YXZ`),Fh=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 V(0,0,1),this._restQuatLeftEye=new B,this._restQuatRightEye=new B,this._restLeftEyeParentWorldQuat=new B,this._restRightEyeParentWorldQuat=new B;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),_h(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),_h(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?Ph.x=-ri.DEG2RAD*this.rangeMapVerticalDown.map(-t):Ph.x=ri.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Ph.y=-ri.DEG2RAD*this.rangeMapHorizontalInner.map(-e):Ph.y=ri.DEG2RAD*this.rangeMapHorizontalOuter.map(e),Mh.setFromEuler(Ph),this._getWorldFaceFrontQuat(Nh),i.quaternion.copy(Nh).multiply(Mh).multiply(Nh.invert()),Mh.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(Mh).premultiply(Mh.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?Ph.x=-ri.DEG2RAD*this.rangeMapVerticalDown.map(-t):Ph.x=ri.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?Ph.y=-ri.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):Ph.y=ri.DEG2RAD*this.rangeMapHorizontalInner.map(e),Mh.setFromEuler(Ph),this._getWorldFaceFrontQuat(Nh),a.quaternion.copy(Nh).multiply(Mh).multiply(Nh.invert()),Mh.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(Mh).premultiply(Mh.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=ri.RAD2DEG*e.y,n=ri.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(jh)<.01)return e.identity();let[t,n]=vh(this.faceFront);return Ph.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(Ph)}};Fh.type=`bone`;var Ih=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=ri.RAD2DEG*e.y,n=ri.RAD2DEG*e.x;this.applyYawPitch(t,n)}};Ih.type=`expression`;var Lh=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*Sm(e/this.inputMaxValue)}},Rh=new Set([`1.0`,`1.0-beta`]),zh=.01,Bh=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return gm(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 gm(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 gm(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(!Rh.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 Ih(n,s,c,l,u):new Fh(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<zh&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=zh),new Lh(n,r)}_v0Import(e,t,n){return gm(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 Ih(n,a,o,s,c):new Fh(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 Fh&&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<zh&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=zh),new Lh(r,i)}_importLookAt(e,t){let n=new Ah(e,t);if(this.helperRoot){let e=new mh(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function Vh(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 Hh=new Set([`1.0`,`1.0-beta`]),Uh=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 gm(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return gm(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return gm(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(!Hh.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 gm(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 gm(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 Fc().loadAsync(Vh(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},Wh=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()}},Gh=class extends Wh{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)})}},Kh=Object.defineProperty,qh=Object.getOwnPropertySymbols,Jh=Object.prototype.hasOwnProperty,Yh=Object.prototype.propertyIsEnumerable,Xh=(e,t,n)=>t in e?Kh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zh=(e,t)=>{for(var n in t||={})Jh.call(t,n)&&Xh(e,n,t[n]);if(qh)for(var n of qh(t))Yh.call(t,n)&&Xh(e,n,t[n]);return e},Qh=(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 $h(e,t){e.colorSpace=t}var eg=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 W().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return Qh(this,null,function*(){let r=Qh(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&&$h(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return Qh(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},tg=`// #define PHONG
4105
4105
 
4106
4106
  varying vec3 vViewPosition;
4107
4107
 
@@ -5034,7 +5034,7 @@ void main() {
5034
5034
  }
5035
5035
  `,rg={None:`none`,Normal:`normal`,LitShadeRate:`litShadeRate`,UV:`uv`},ig={None:`none`,WorldCoordinates:`worldCoordinates`,ScreenCoordinates:`screenCoordinates`};function ag(e){return e.colorSpace}var og=class extends tc{constructor(e={}){super({vertexShader:tg,fragmentShader:ng}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=0,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=rg.None,this._outlineWidthMode=ig.None,this._isOutline=!1,e.transparentWithZWrite&&(e.depthWrite=!0),delete e.transparentWithZWrite,e.fog=!0,e.lights=!0,e.clipping=!0,this.uniforms=Qs.merge([J.common,J.normalmap,J.emissivemap,J.fog,J.lights,{litFactor:{value:new W(1,1,1)},mapUvTransform:{value:new H},colorAlpha:{value:1},normalMapUvTransform:{value:new H},shadeColorFactor:{value:new W(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new H},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new H},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new W(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new H},parametricRimColorFactor:{value:new W(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new H},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new W(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new H},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new H},outlineWidthFactor:{value:0},outlineColorFactor:{value:new W(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new H},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},e.uniforms??{}]),this.setValues(e),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([e,t])=>`${e}:${t}`),this.matcapTexture?`matcapTextureColorSpace:${ag(this.matcapTexture)}`:``,this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${ag(this.shadeMultiplyTexture)}`:``,this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${ag(this.rimMultiplyTexture)}`:``].join(`,`),this.onBeforeCompile=e=>{let t=Object.entries(Zh(Zh({},this._generateDefines()),this.defines)).filter(([e,t])=>!!t).map(([e,t])=>`#define ${e} ${t}`).join(`
5036
5036
  `)+`
5037
- `;e.vertexShader=t+e.vertexShader,e.fragmentShader=t+e.fragmentShader}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:184,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode===`normal`,DEBUG_LITSHADERATE:this._debugMode===`litShadeRate`,DEBUG_UV:this._debugMode===`uv`,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===ig.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}},sg=new Set([`1.0`,`1.0-beta`]),cg=class e{get name(){return e.EXTENSION_NAME}constructor(e,t={}){this.parser=e,this.materialType=t.materialType??og,this.renderOrderOffset=t.renderOrderOffset??0,this.v0CompatShade=t.v0CompatShade??!1,this.debugMode=t.debugMode??`none`,this._mToonMaterialSet=new Set}beforeRoot(){return Qh(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return Qh(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){let n=this._getMToonExtension(e);return n?this._extendMaterialParams(n,t):null}loadMesh(e){return Qh(this,null,function*(){let t=this.parser,n=t.json.meshes?.[e];if(n==null)throw Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let r=n.primitives,i=yield t.loadMesh(e);if(r.length===1){let e=i,t=r[0].material;t!=null&&this._setupPrimitive(e,t)}else{let e=i;for(let t=0;t<r.length;t++){let n=e.children[t],i=r[t].material;i!=null&&this._setupPrimitive(n,i)}}return i})}_removeUnlitExtensionIfMToonExists(){this.parser.json.materials?.map((e,t)=>{this._getMToonExtension(t)&&e.extensions?.KHR_materials_unlit&&delete e.extensions.KHR_materials_unlit})}_getMToonExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r==null)return;let i=r.specVersion;if(!sg.has(i)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${i}"`);return}return r}_extendMaterialParams(e,t){return Qh(this,null,function*(){delete t.metalness,delete t.roughness;let n=new eg(this.parser,t);n.assignPrimitive(`transparentWithZWrite`,e.transparentWithZWrite),n.assignColor(`shadeColorFactor`,e.shadeColorFactor),n.assignTexture(`shadeMultiplyTexture`,e.shadeMultiplyTexture,!0),n.assignPrimitive(`shadingShiftFactor`,e.shadingShiftFactor),n.assignTexture(`shadingShiftTexture`,e.shadingShiftTexture,!0),n.assignPrimitive(`shadingShiftTextureScale`,e.shadingShiftTexture?.scale),n.assignPrimitive(`shadingToonyFactor`,e.shadingToonyFactor),n.assignPrimitive(`giEqualizationFactor`,e.giEqualizationFactor),n.assignColor(`matcapFactor`,e.matcapFactor),n.assignTexture(`matcapTexture`,e.matcapTexture,!0),n.assignColor(`parametricRimColorFactor`,e.parametricRimColorFactor),n.assignTexture(`rimMultiplyTexture`,e.rimMultiplyTexture,!0),n.assignPrimitive(`rimLightingMixFactor`,e.rimLightingMixFactor),n.assignPrimitive(`parametricRimFresnelPowerFactor`,e.parametricRimFresnelPowerFactor),n.assignPrimitive(`parametricRimLiftFactor`,e.parametricRimLiftFactor),n.assignPrimitive(`outlineWidthMode`,e.outlineWidthMode),n.assignPrimitive(`outlineWidthFactor`,e.outlineWidthFactor),n.assignTexture(`outlineWidthMultiplyTexture`,e.outlineWidthMultiplyTexture,!1),n.assignColor(`outlineColorFactor`,e.outlineColorFactor),n.assignPrimitive(`outlineLightingMixFactor`,e.outlineLightingMixFactor),n.assignTexture(`uvAnimationMaskTexture`,e.uvAnimationMaskTexture,!1),n.assignPrimitive(`uvAnimationScrollXSpeedFactor`,e.uvAnimationScrollXSpeedFactor),n.assignPrimitive(`uvAnimationScrollYSpeedFactor`,e.uvAnimationScrollYSpeedFactor),n.assignPrimitive(`uvAnimationRotationSpeedFactor`,e.uvAnimationRotationSpeedFactor),n.assignPrimitive(`v0CompatShade`,this.v0CompatShade),n.assignPrimitive(`debugMode`,this.debugMode),yield n.pending})}_setupPrimitive(e,t){let n=this._getMToonExtension(t);if(n){e.renderOrder=this._parseRenderOrder(n)+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode==`string`&&e.outlineWidthMode!==`none`&&typeof e.outlineWidthFactor==`number`&&e.outlineWidthFactor>0}_generateOutline(e){let t=e.material;if(!(t instanceof uo)||!this._shouldGenerateOutline(t))return;e.material=[t];let n=t.clone();n.name+=` (Outline)`,n.isOutline=!0,n.side=1,e.material.push(n);let r=e.geometry,i=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,i,0),r.addGroup(0,i,1)}_addToMaterialSet(e){let t=e.material,n=new Set;Array.isArray(t)?t.forEach(e=>n.add(e)):n.add(t);for(let e of n)this._mToonMaterialSet.add(e)}_parseRenderOrder(e){return(e.transparentWithZWrite?0:19)+(e.renderQueueOffsetNumber??0)}};cg.EXTENSION_NAME=`VRMC_materials_mtoon`;var lg=cg,ug=(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())}),dg=class e{get name(){return e.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return ug(this,null,function*(){let n=this._getHDREmissiveMultiplierExtension(e);n!=null&&(console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead."),t.emissiveIntensity=n.emissiveMultiplier)})}_getHDREmissiveMultiplierExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r!=null)return r}};dg.EXTENSION_NAME=`VRMC_materials_hdr_emissiveMultiplier`;var fg=dg,pg=Object.defineProperty,mg=Object.defineProperties,hg=Object.getOwnPropertyDescriptors,gg=Object.getOwnPropertySymbols,_g=Object.prototype.hasOwnProperty,vg=Object.prototype.propertyIsEnumerable,yg=(e,t,n)=>t in e?pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bg=(e,t)=>{for(var n in t||={})_g.call(t,n)&&yg(e,n,t[n]);if(gg)for(var n of gg(t))vg.call(t,n)&&yg(e,n,t[n]);return e},xg=(e,t)=>mg(e,hg(t)),Sg=(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 Cg(e){return e**2.2}var wg=class{get name(){return`VRMMaterialsV0CompatPlugin`}constructor(e){this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let t=this.parser.json;t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.indexOf(`KHR_texture_transform`)===-1&&t.extensionsUsed.push(`KHR_texture_transform`)}beforeRoot(){return Sg(this,null,function*(){let e=this.parser.json,t=e.extensions?.VRM?.materialProperties;t&&(this._populateRenderQueueMap(t),t.forEach((t,n)=>{let r=e.materials?.[n];if(r==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${n}] of glTF but the material doesn't exist`);return}if(t.shader===`VRM/MToon`){let i=this._parseV0MToonProperties(t,r);e.materials[n]=i}else if(t.shader?.startsWith(`VRM/Unlit`)){let i=this._parseV0UnlitProperties(t,r);e.materials[n]=i}else t.shader===`VRM_USE_GLTFSHADER`||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${t.shader}`)}))})}_parseV0MToonProperties(e,t){let n=e.keywordMap?._ALPHABLEND_ON??!1,r=e.floatProperties?._ZWrite===1&&n,i=this._v0ParseRenderQueue(e),a=e.keywordMap?._ALPHATEST_ON??!1,o=n?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=(e.floatProperties?._CullMode??2)===0,l=this._portTextureTransform(e),u=(e.vectorProperties?._Color??[1,1,1,1]).map((e,t)=>t===3?e:Cg(e)),d=e.textureProperties?._MainTex,f=d==null?void 0:{index:d,extensions:bg({},l)},p=e.floatProperties?._BumpScale??1,m=e.textureProperties?._BumpMap,h=m==null?void 0:{index:m,scale:p,extensions:bg({},l)},g=(e.vectorProperties?._EmissionColor??[0,0,0,1]).map(Cg),_=e.textureProperties?._EmissionMap,v=_==null?void 0:{index:_,extensions:bg({},l)},y=(e.vectorProperties?._ShadeColor??[.97,.81,.86,1]).map(Cg),b=e.textureProperties?._ShadeTexture,x=b==null?void 0:{index:b,extensions:bg({},l)},S=e.floatProperties?._ShadeShift??0,C=e.floatProperties?._ShadeToony??.9;C=ri.lerp(C,1,.5+.5*S),S=-S-(1-C);let w=e.floatProperties?._IndirectLightIntensity??.1,T=w?1-w:void 0,E=e.textureProperties?._SphereAdd,D=E==null?void 0:[1,1,1],O=E==null?void 0:{index:E},ee=e.floatProperties?._RimLightingMix??0,k=e.textureProperties?._RimTexture,te=k==null?void 0:{index:k,extensions:bg({},l)},ne=(e.vectorProperties?._RimColor??[0,0,0,1]).map(Cg),re=e.floatProperties?._RimFresnelPower??1,ie=e.floatProperties?._RimLift??0,ae=[`none`,`worldCoordinates`,`screenCoordinates`][e.floatProperties?._OutlineWidthMode??0],oe=e.floatProperties?._OutlineWidth??0;oe=.01*oe;let se=e.textureProperties?._OutlineWidthTexture,ce=se==null?void 0:{index:se,extensions:bg({},l)},le=(e.vectorProperties?._OutlineColor??[0,0,0]).map(Cg),ue=(e.floatProperties?._OutlineColorMode??0)===1?e.floatProperties?._OutlineLightingMix??1:0,de=e.textureProperties?._UvAnimMaskTexture,fe=de==null?void 0:{index:de,extensions:bg({},l)},A=e.floatProperties?._UvAnimScrollX??0,pe=e.floatProperties?._UvAnimScrollY??0;pe!=null&&(pe=-pe);let me=e.floatProperties?._UvAnimRotation??0,j={specVersion:`1.0`,transparentWithZWrite:r,renderQueueOffsetNumber:i,shadeColorFactor:y,shadeMultiplyTexture:x,shadingShiftFactor:S,shadingToonyFactor:C,giEqualizationFactor:T,matcapFactor:D,matcapTexture:O,rimLightingMixFactor:ee,rimMultiplyTexture:te,parametricRimColorFactor:ne,parametricRimFresnelPowerFactor:re,parametricRimLiftFactor:ie,outlineWidthMode:ae,outlineWidthFactor:oe,outlineWidthMultiplyTexture:ce,outlineColorFactor:le,outlineLightingMixFactor:ue,uvAnimationMaskTexture:fe,uvAnimationScrollXSpeedFactor:A,uvAnimationScrollYSpeedFactor:pe,uvAnimationRotationSpeedFactor:me};return xg(bg({},t),{pbrMetallicRoughness:{baseColorFactor:u,baseColorTexture:f},normalTexture:h,emissiveTexture:v,emissiveFactor:g,alphaMode:o,alphaCutoff:s,doubleSided:c,extensions:{VRMC_materials_mtoon:j}})}_parseV0UnlitProperties(e,t){let n=e.shader===`VRM/UnlitTransparentZWrite`,r=e.shader===`VRM/UnlitTransparent`||n,i=this._v0ParseRenderQueue(e),a=e.shader===`VRM/UnlitCutout`,o=r?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=this._portTextureTransform(e),l=(e.vectorProperties?._Color??[1,1,1,1]).map(Cg),u=e.textureProperties?._MainTex,d=u==null?void 0:{index:u,extensions:bg({},c)},f={specVersion:`1.0`,transparentWithZWrite:n,renderQueueOffsetNumber:i,shadeColorFactor:l,shadeMultiplyTexture:d};return xg(bg({},t),{pbrMetallicRoughness:{baseColorFactor:l,baseColorTexture:d},alphaMode:o,alphaCutoff:s,extensions:{VRMC_materials_mtoon:f}})}_portTextureTransform(e){let t=e.vectorProperties?._MainTex;if(t==null)return{};let n=[t?.[0]??0,t?.[1]??0],r=[t?.[2]??1,t?.[3]??1];return n[1]=1-r[1]-n[1],{KHR_texture_transform:{offset:n,scale:r}}}_v0ParseRenderQueue(e){let t=e.shader===`VRM/UnlitTransparentZWrite`,n=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||t,r=e.floatProperties?._ZWrite===1||t,i=0;if(n){let t=e.renderQueue;t!=null&&(i=r?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return i}_populateRenderQueueMap(e){let t=new Set,n=new Set;e.forEach(e=>{let r=e.shader===`VRM/UnlitTransparentZWrite`,i=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||r,a=e.floatProperties?._ZWrite===1||r;if(i){let r=e.renderQueue;r!=null&&(a?n.add(r):t.add(r))}}),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach((e,n)=>{let r=Math.min(Math.max(n-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,r)}),Array.from(n).sort().forEach((e,t)=>{let n=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,n)})}},Tg=(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())}),Eg=new V,Dg=class extends $i{constructor(e){super(),this._attrPosition=new G(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(vr);let t=new K;t.setAttribute(`position`,this._attrPosition);let n=new ps({color:16711935,depthTest:!1,depthWrite:!1});this._line=new xs(t,n),this.add(this._line),this.constraint=e}updateMatrixWorld(e){Eg.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Eg.x,Eg.y,Eg.z),this.constraint.source&&Eg.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Eg.x,Eg.y,Eg.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}};function Og(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}var kg=new V,Ag=new V;function jg(e,t){return e.decompose(kg,t,Ag),t}function Mg(e){return e.invert?e.invert():e.inverse(),e}var Ng=class{constructor(e,t){this.destination=e,this.source=t,this.weight=1}},Pg=new V,Fg=new V,Ig=new V,Lg=new B,Rg=new B,zg=new B,Bg=class extends Ng{get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set(e===`PositiveX`?1:e===`NegativeX`?-1:0,e===`PositiveY`?1:e===`NegativeY`?-1:0,e===`PositiveZ`?1:e===`NegativeZ`?-1:0)}get dependencies(){let e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}constructor(e,t){super(e,t),this._aimAxis=`PositiveX`,this._v3AimAxis=new V(1,0,0),this._dstRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let e=Lg.identity(),t=Rg.identity();this.destination.parent&&(jg(this.destination.parent.matrixWorld,e),Mg(t.copy(e)));let n=Pg.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),r=Og(this.source.matrixWorld,Fg).sub(Og(this.destination.matrixWorld,Ig)).normalize(),i=zg.setFromUnitVectors(n,r).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}};function Vg(e,t){let n=[e],r=e.parent;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}var Hg=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);t??(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e),this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.setInitState())}update(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.update())}_processConstraint(e,t,n,r){if(n.has(e))return;if(t.has(e))throw Error(`VRMNodeConstraintManager: Circular dependency detected while updating constraints`);t.add(e);let i=e.dependencies;for(let e of i)Vg(e,e=>{let i=this._objectConstraintsMap.get(e);if(i)for(let e of i)this._processConstraint(e,t,n,r)});r(e),n.add(e)}},Ug=new B,Wg=new B,Gg=class extends Ng{get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._dstRestQuat=new B,this._invSrcRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Mg(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let e=Ug.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=Wg.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}},Kg=new V,qg=new B,Jg=new B,Yg=class extends Ng{get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set(+(e===`X`),+(e===`Y`),+(e===`Z`))}get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._rollAxis=`X`,this._v3RollAxis=new V(1,0,0),this._dstRestQuat=new B,this._invDstRestQuat=new B,this._invSrcRestQuatMulDstRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Mg(this._invDstRestQuat.copy(this._dstRestQuat)),Mg(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let e=qg.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=Kg.copy(this._v3RollAxis).applyQuaternion(e),n=Jg.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(n,this.weight)}},Xg=new Set([`1.0`,`1.0-beta`]),Zg=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return Tg(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(t){return Tg(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let r=new Hg,i=yield this.parser.getDependencies(`node`);return i.forEach((t,a)=>{let o=n.nodes[a]?.extensions?.[e.EXTENSION_NAME];if(o==null)return;let s=o.specVersion;if(!Xg.has(s)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`);return}let c=o.constraint;if(c.roll!=null){let e=this._importRollConstraint(t,i,c.roll);r.addConstraint(e)}else if(c.aim!=null){let e=this._importAimConstraint(t,i,c.aim);r.addConstraint(e)}else if(c.rotation!=null){let e=this._importRotationConstraint(t,i,c.rotation);r.addConstraint(e)}}),t.scene.updateMatrixWorld(),r.setInitState(),r})}_importRollConstraint(e,t,n){let{source:r,rollAxis:i,weight:a}=n,o=t[r],s=new Yg(e,o);if(i!=null&&(s.rollAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new Dg(s);this.helperRoot.add(e)}return s}_importAimConstraint(e,t,n){let{source:r,aimAxis:i,weight:a}=n,o=t[r],s=new Bg(e,o);if(i!=null&&(s.aimAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new Dg(s);this.helperRoot.add(e)}return s}_importRotationConstraint(e,t,n){let{source:r,weight:i}=n,a=t[r],o=new Gg(e,a);if(i!=null&&(o.weight=i),this.helperRoot){let e=new Dg(o);this.helperRoot.add(e)}return o}};Zg.EXTENSION_NAME=`VRMC_node_constraint`;var Qg=Zg,$g=(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())}),e_=class{},t_=new V,n_=new V,r_=class extends e_{get type(){return`capsule`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.tail=e?.tail??new V(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){t_.setFromMatrixPosition(e),n_.subVectors(this.tail,this.offset).applyMatrix4(e),n_.sub(t_);let i=n_.lengthSq();r.copy(t).sub(t_);let a=n_.dot(r);a<=0||(i<=a||n_.multiplyScalar(a/i),r.sub(n_));let o=r.length(),s=this.inside?this.radius-n-o:o-n-this.radius;return s<0&&(r.multiplyScalar(1/o),this.inside&&r.negate()),s}},i_=new V,a_=new H,o_=class extends e_{get type(){return`plane`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.normal=e?.normal??new V(0,0,1)}calculateCollision(e,t,n,r){r.setFromMatrixPosition(e),r.negate().add(t),a_.getNormalMatrix(e),i_.copy(this.normal).applyNormalMatrix(a_).normalize();let i=r.dot(i_)-n;return r.copy(i_),i}},s_=new V,c_=class extends e_{get type(){return`sphere`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){r.subVectors(t,s_.setFromMatrixPosition(e));let i=r.length(),a=this.inside?this.radius-n-i:i-n-this.radius;return a<0&&(r.multiplyScalar(1/i),this.inside&&r.negate()),a}},l_=new V,u_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new V,this._currentTail=new V,this._shape=e,this._attrPos=new G(new Float32Array(396),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);let n=l_.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),e=!0),e&&this._buildPosition()}_buildPosition(){l_.copy(this._currentTail).sub(this._currentOffset);let e=l_.length()/this._currentRadius;for(let t=0;t<=16;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(n),-Math.cos(n),0),this._attrPos.setXYZ(17+t,e+Math.sin(n),Math.cos(n),0),this._attrPos.setXYZ(34+t,-Math.sin(n),0,-Math.cos(n)),this._attrPos.setXYZ(51+t,e+Math.sin(n),0,Math.cos(n))}for(let t=0;t<32;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(n),Math.cos(n)),this._attrPos.setXYZ(100+t,e,Math.sin(n),Math.cos(n))}let t=Math.atan2(l_.y,Math.sqrt(l_.x*l_.x+l_.z*l_.z)),n=-Math.atan2(l_.z,l_.x);this.rotateZ(t),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){let t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}},d_=class extends K{constructor(e){super(),this.worldScale=1,this._currentOffset=new V,this._currentNormal=new V,this._shape=e,this._attrPos=new G(new Float32Array(18),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},f_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new V,this._shape=e,this._attrPos=new G(new Float32Array(288),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),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._currentOffset.x,this._currentOffset.y,this._currentOffset.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.needsUpdate=!0}},p_=new V,m_=class extends $i{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof c_)this._geometry=new f_(this.collider.shape);else if(this.collider.shape instanceof r_)this._geometry=new u_(this.collider.shape);else if(this.collider.shape instanceof o_)this._geometry=new d_(this.collider.shape);else throw Error(`VRMSpringBoneColliderHelper: Unknown collider shape type detected`);let t=new ps({color:16711935,depthTest:!1,depthWrite:!1});this._line=new Ts(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=p_.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},h_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new V,this._springBone=e,this._attrPos=new G(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),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}},g_=new V,__=class extends $i{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new h_(this.springBone);let t=new ps({color:16776960,depthTest:!1,depthWrite:!1});this._line=new Ts(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=g_.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},v_=class extends Qi{constructor(e){super(),this.colliderMatrix=new U,this.shape=e}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),y_(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function y_(e,t,n){let r=t.elements;e.copy(t),n&&(e.elements[12]=r[0]*n.x+r[4]*n.y+r[8]*n.z+r[12],e.elements[13]=r[1]*n.x+r[5]*n.y+r[9]*n.z+r[13],e.elements[14]=r[2]*n.x+r[6]*n.y+r[10]*n.z+r[14])}var b_=new U;function x_(e){return e.invert?e.invert():e.getInverse(b_.copy(e)),e}var S_=class{constructor(e){this._inverseCache=new U,this._shouldUpdateInverse=!0,this.matrix=e;let t={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&=(x_(this._inverseCache.copy(this.matrix)),!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},C_=new U,w_=new V,T_=new V,E_=new V,D_=new V,O_=new U,k_=class{constructor(e,t,n={},r=[]){this._currentTail=new V,this._prevTail=new V,this._boneAxis=new V,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new U,this._initialLocalRotation=new B,this._initialLocalChildPosition=new V,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:n.hitRadius??0,stiffness:n.stiffness??1,gravityPower:n.gravityPower??0,gravityDir:n.gravityDir?.clone()??new V(0,-1,0),dragForce:n.dragForce??.4},this.colliderGroups=r}get dependencies(){let e=new Set,t=this.bone.parent;t&&e.add(t);for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++)e.add(this.colliderGroups[t].colliders[n]);return e}get center(){return this._center}set center(e){this._center?.userData.inverseCacheProxy&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new S_(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:C_}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength();let t=T_.copy(this._boneAxis).transformDirection(this._initialLocalMatrix).transformDirection(this._parentMatrixWorld);D_.copy(this._currentTail).add(w_.subVectors(this._currentTail,this._prevTail).multiplyScalar(1-this.settings.dragForce)).applyMatrix4(this._getMatrixCenterToWorld()).addScaledVector(t,this.settings.stiffness*e).addScaledVector(this.settings.gravityDir,this.settings.gravityPower*e),E_.setFromMatrixPosition(this.bone.matrixWorld),D_.sub(E_).normalize().multiplyScalar(this._worldSpaceBoneLength).add(E_),this._collision(D_),this._prevTail.copy(this._currentTail),this._currentTail.copy(D_).applyMatrix4(this._getMatrixWorldToCenter());let n=O_.multiplyMatrices(this._parentMatrixWorld,this._initialLocalMatrix).invert();this.bone.quaternion.setFromUnitVectors(this._boneAxis,w_.copy(D_).applyMatrix4(n).normalize()).premultiply(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++){let r=this.colliderGroups[t].colliders[n],i=r.shape.calculateCollision(r.colliderMatrix,e,this.settings.hitRadius,w_);if(i<0){e.addScaledVector(w_,-i),e.sub(E_);let t=e.length();e.multiplyScalar(this._worldSpaceBoneLength/t).add(E_)}}}_calcWorldSpaceBoneLength(){w_.setFromMatrixPosition(this.bone.matrixWorld),this.child?T_.setFromMatrixPosition(this.child.matrixWorld):(T_.copy(this._initialLocalChildPosition),T_.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=w_.sub(T_).length()}_getMatrixCenterToWorld(){return this._center?this._center.matrixWorld:C_}_getMatrixWorldToCenter(){return this._center?this._center.userData.inverseCacheProxy.inverse:C_}};function A_(e,t){let n=[],r=e;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}function j_(e,t){e.children.forEach(e=>{t(e)||j_(e,t)})}function M_(e){let t=new Map;for(let n of e){let r=n;do{let n=(t.get(r)??0)+1;if(n===e.size)return r;t.set(r,n),r=r.parent}while(r!==null)}return null}var N_=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn(`VRMSpringBoneManager: springBones is deprecated. use joints instead.`),this._joints}get colliderGroups(){let e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(t=>{e.add(t)})}),Array.from(e)}get colliders(){let e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(t=>{e.add(t)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t??(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e),this._isSortedJointsDirty=!0}addSpringBone(e){console.warn(`VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead.`),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e),this._isSortedJointsDirty=!0}deleteSpringBone(e){console.warn(`VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead.`),this.deleteJoint(e)}setInitState(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.setInitState()}}reset(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.reset()}}update(e){this._sortJoints();for(let e=0;e<this._ancestors.length;e++)this._ancestors[e].updateWorldMatrix(e===0,!1);for(let t=0;t<this._sortedJoints.length;t++){let n=this._sortedJoints[t];n.bone.updateMatrix(),n.bone.updateWorldMatrix(!1,!1),n.update(e),j_(n.bone,this._relevantChildrenUpdated)}}_sortJoints(){if(!this._isSortedJointsDirty)return;let e=[],t=new Set,n=new Set,r=new Set;for(let i of this._joints)this._insertJointSort(i,t,n,e,r);this._sortedJoints=e;let i=M_(r);this._ancestors=[],i&&(this._ancestors.push(i),j_(i,e=>(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(this._ancestors.push(e),!1))),this._isSortedJointsDirty=!1}_insertJointSort(e,t,n,r,i){if(n.has(e))return;if(t.has(e)){this._hasWarnedCircularDependency||=(console.warn(`VRMSpringBoneManager: Circular dependency detected`),!0);return}t.add(e);let a=e.dependencies;for(let e of a){let a=!1,o=null;A_(e,e=>{let s=this._objectSpringBonesMap.get(e);if(s)for(let e of s)a=!0,this._insertJointSort(e,t,n,r,i);else a||(o=e)}),o&&i.add(o)}r.push(e),n.add(e)}_relevantChildrenUpdated(e){return(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(e.updateWorldMatrix(!1,!1),!1)}},P_=`VRMC_springBone_extended_collider`,F_=new Set([`1.0`,`1.0-beta`]),I_=new Set([`1.0`]),L_=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.jointHelperRoot=t?.jointHelperRoot,this.colliderHelperRoot=t?.colliderHelperRoot,this.useExtendedColliders=t?.useExtendedColliders??!0}afterRoot(e){return $g(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return $g(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(t){return $g(this,null,function*(){var n;let r=t.parser.json;if(r.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let i=new N_,a=yield t.parser.getDependencies(`node`),o=r.extensions?.[e.EXTENSION_NAME];if(!o)return null;let s=o.specVersion;if(!F_.has(s))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`),null;let c=o.colliders?.map((t,n)=>{let r=a[t.node];if(r==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} attempted to reference a node #${t.node} but not found. Skipping the collider`),null;let i=t.shape,o=t.extensions?.[P_];if(this.useExtendedColliders&&o!=null){let t=o.specVersion;if(!I_.has(t))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${P_} specVersion "${t}". Fallbacking to the ${e.EXTENSION_NAME} definition`);else{let e=o.shape;if(e.sphere)return this._importSphereCollider(r,{offset:new V().fromArray(e.sphere.offset??[0,0,0]),radius:e.sphere.radius??0,inside:e.sphere.inside??!1});if(e.capsule)return this._importCapsuleCollider(r,{offset:new V().fromArray(e.capsule.offset??[0,0,0]),radius:e.capsule.radius??0,tail:new V().fromArray(e.capsule.tail??[0,0,0]),inside:e.capsule.inside??!1});if(e.plane)return this._importPlaneCollider(r,{offset:new V().fromArray(e.plane.offset??[0,0,0]),normal:new V().fromArray(e.plane.normal??[0,0,1])})}}if(i.sphere)return this._importSphereCollider(r,{offset:new V().fromArray(i.sphere.offset??[0,0,0]),radius:i.sphere.radius??0,inside:!1});if(i.capsule)return this._importCapsuleCollider(r,{offset:new V().fromArray(i.capsule.offset??[0,0,0]),radius:i.capsule.radius??0,tail:new V().fromArray(i.capsule.tail??[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} has no valid shape. Skipping the collider`)}),l=o.colliderGroups?.map((e,t)=>({colliders:(e.colliders??[]).map(e=>c?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a collider #${e} but not found. Skipping the collider`),null)).filter(e=>e!=null),name:e.name}));return(n=o.springs)==null||n.forEach((e,t)=>{let n=e.joints,r=e.colliderGroups?.map(e=>l?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null),o=e.center==null?void 0:a[e.center],s;n.forEach(e=>{if(s){let t=a[s.node],n=a[e.node],c={hitRadius:s.hitRadius,dragForce:s.dragForce,gravityPower:s.gravityPower,stiffness:s.stiffness,gravityDir:s.gravityDir==null?void 0:new V().fromArray(s.gravityDir)},l=this._importJoint(t,n,c,r);o&&(l.center=o),i.addJoint(l)}s=e})}),i.setInitState(),i})}_v0Import(e){return $g(this,null,function*(){let t=e.parser.json;if(t.extensionsUsed?.indexOf(`VRM`)===-1)return null;let n=t.extensions?.VRM?.secondaryAnimation;if(!n)return null;let r=n?.boneGroups;if(!r)return null;let i=new N_,a=yield e.parser.getDependencies(`node`),o=n.colliderGroups?.map((e,t)=>{let n=a[e.node];return n==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a node #${e.node} but not found. Skipping the collider group`),null):{colliders:(e.colliders??[]).map((e,t)=>{let r=new V(0,0,0);return e.offset&&r.set(e.offset.x??0,e.offset.y??0,e.offset.z?-e.offset.z:0),this._importSphereCollider(n,{offset:r,radius:e.radius??0,inside:!1})})}});return r?.forEach((e,t)=>{let n=e.bones;n&&n.forEach(n=>{let r=a[n];if(r==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${t} attempted to reference a node #${n} but not found. Skipping the node`);return}let s=new V;e.gravityDir?s.set(e.gravityDir.x??0,e.gravityDir.y??0,e.gravityDir.z??0):s.set(0,-1,0);let c=e.center==null?void 0:a[e.center],l={hitRadius:e.hitRadius,dragForce:e.dragForce,gravityPower:e.gravityPower,stiffness:e.stiffiness,gravityDir:s},u=e.colliderGroups?.map(e=>o?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null);r.traverse(e=>{let t=e.children[0]??null,n=this._importJoint(e,t,l,u);c&&(n.center=c),i.addJoint(n)})})}),e.scene.updateMatrixWorld(),i.setInitState(),i})}_importJoint(e,t,n,r){let i=new k_(e,t,n,r);if(this.jointHelperRoot){let e=new __(i);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return i}_importSphereCollider(e,t){let n=new v_(new c_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importCapsuleCollider(e,t){let n=new v_(new r_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importPlaneCollider(e,t){let n=new v_(new o_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}};L_.EXTENSION_NAME=`VRMC_springBone`;var R_=L_,z_=class{get name(){return`VRMLoaderPlugin`}constructor(e,t){this.parser=e;let n=t?.helperRoot,r=t?.autoUpdateHumanBones;this.expressionPlugin=t?.expressionPlugin??new Fm(e),this.firstPersonPlugin=t?.firstPersonPlugin??new zm(e),this.humanoidPlugin=t?.humanoidPlugin??new ih(e,{helperRoot:n,autoUpdateHumanBones:r}),this.lookAtPlugin=t?.lookAtPlugin??new Bh(e,{helperRoot:n}),this.metaPlugin=t?.metaPlugin??new Uh(e),this.mtoonMaterialPlugin=t?.mtoonMaterialPlugin??new lg(e),this.materialsHDREmissiveMultiplierPlugin=t?.materialsHDREmissiveMultiplierPlugin??new fg(e),this.materialsV0CompatPlugin=t?.materialsV0CompatPlugin??new wg(e),this.springBonePlugin=t?.springBonePlugin??new R_(e,{colliderHelperRoot:n,jointHelperRoot:n}),this.nodeConstraintPlugin=t?.nodeConstraintPlugin??new Qg(e,{helperRoot:n})}beforeRoot(){return hm(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return hm(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){return this.mtoonMaterialPlugin.getMaterialType(e)??null}extendMaterialParams(e,t){return hm(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return hm(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let t=e.userData.vrmMeta,n=e.userData.vrmHumanoid;if(t&&n){let r=new Gh({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:n,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};function B_(e){let t=new Set;return e.traverse(e=>{if(!e.isMesh)return;let n=e;t.add(n)}),t}function V_(e,t,n){if(t.size===1){let n=t.values().next().value;if(n.weight===1)return e[n.index]}let r=new Float32Array(e[0].count*3),i=0;if(n)i=1;else for(let e of t)i+=e.weight;for(let n of t){let t=e[n.index],a=n.weight/i;for(let e=0;e<t.count;e++)r[e*3+0]+=t.getX(e)*a,r[e*3+1]+=t.getY(e)*a,r[e*3+2]+=t.getZ(e)*a}return new G(r,3)}function H_(e){let t=B_(e.scene),n=new Map,r=e.expressionManager?.expressionMap;if(r!=null)for(let[e,t]of Object.entries(r)){let r=new Set;for(let i of t.binds)if(i instanceof km){if(i.weight!==0)for(let t of i.primitives){let r=n.get(t);r??(r=new Map,n.set(t,r));let a=r.get(e);a??(a=new Set,r.set(e,a)),a.add(i)}r.add(i)}for(let e of r)t.deleteBind(e)}for(let e of t){let t=n.get(e);if(t==null)continue;let i=e.geometry.morphAttributes;e.geometry.morphAttributes={};let a=e.geometry.clone();e.geometry=a;let o=a.morphTargetsRelative,s=i.position!=null,c=i.normal!=null,l={},u={},d=[];if(s||c){s&&(l.position=[]),c&&(l.normal=[]);let n=0;for(let[a,f]of t)s&&(l.position[n]=V_(i.position,f,o)),c&&(l.normal[n]=V_(i.normal,f,o)),r?.[a].addBind(new km({index:n,weight:1,primitives:[e]})),u[a]=n,d.push(0),n++}a.morphAttributes=l,e.morphTargetDictionary=u,e.morphTargetInfluences=d}}function U_(e,t,n){if(e.getComponent)return e.getComponent(t,n);{let r=e.array[t*e.itemSize+n];return e.normalized&&(r=ri.denormalize(r,e.array)),r}}function W_(e,t,n,r){e.setComponent?e.setComponent(t,n,r):(e.normalized&&(r=ri.normalize(r,e.array)),e.array[t*e.itemSize+n]=r)}function G_(e){let t=K_(e),n=new Set;for(let e of t)n.has(e.geometry)&&(e.geometry=$_(e.geometry)),n.add(e.geometry);let r=new Map;for(let e of n){let t=e.getAttribute(`skinIndex`),n=r.get(t)??new Map;r.set(t,n);let i=e.getAttribute(`skinWeight`),a=q_(t,i);n.set(i,a)}let i=new Map;for(let e of t){let t=J_(e,r);i.set(e,t)}let a=[];for(let[e,t]of i){let n=!1;for(let r of a)if(Y_(t,r.boneInverseMap)){n=!0,r.meshes.add(e);for(let[e,n]of t)r.boneInverseMap.set(e,n);break}n||a.push({boneInverseMap:t,meshes:new Set([e])})}let o=new Map,s=new Q_,c=new Q_,l=new Q_;for(let e of a){let{boneInverseMap:t,meshes:n}=e,r=Array.from(t.keys()),i=new Yo(r,Array.from(t.values())),a=c.getOrCreate(i);for(let e of n){let t=e.geometry.getAttribute(`skinIndex`),n=s.getOrCreate(t),i=e.skeleton.bones,c=`${n};${a};${i.map(e=>l.getOrCreate(e)).join(`,`)}`,u=o.get(c);u??(u=t.clone(),X_(u,i,r),o.set(c,u)),e.geometry.setAttribute(`skinIndex`,u)}for(let e of n)e.bind(i,new U)}}function K_(e){let t=new Set;return e.traverse(e=>{if(!e.isSkinnedMesh)return;let n=e;t.add(n)}),t}function q_(e,t){let n=new Set;for(let r=0;r<e.count;r++)for(let i=0;i<e.itemSize;i++){let a=U_(e,r,i);U_(t,r,i)!==0&&n.add(a)}return n}function J_(e,t){let n=new Map,r=e.skeleton,i=e.geometry,a=i.getAttribute(`skinIndex`),o=i.getAttribute(`skinWeight`),s=t.get(a)?.get(o);if(!s)throw Error(`Unreachable. attributeUsedIndexSetMap does not know the skin index attribute or the skin weight attribute.`);for(let e of s)n.set(r.bones[e],r.boneInverses[e]);return n}function Y_(e,t){for(let[n,r]of e.entries()){let e=t.get(n);if(e!=null&&!Z_(r,e))return!1}return!0}function X_(e,t,n){let r=new Map;for(let e of t)r.set(e,r.size);let i=new Map;for(let[e,t]of n.entries()){let n=r.get(t);i.set(n,e)}for(let t=0;t<e.count;t++)for(let n=0;n<e.itemSize;n++){let r=U_(e,t,n),a=i.get(r);W_(e,t,n,a)}e.needsUpdate=!0}function Z_(e,t,n){if(n||=1e-4,e.elements.length!=t.elements.length)return!1;for(let r=0,i=e.elements.length;r<i;r++)if(Math.abs(e.elements[r]-t.elements[r])>n)return!1;return!0}var Q_=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(e){return this._objectIndexMap.get(e)}getOrCreate(e){let t=this._objectIndexMap.get(e);return t??(t=this._index,this._objectIndexMap.set(e,t),this._index++),t}};function $_(e){let t=new K;t.name=e.name,t.setIndex(e.index);for(let[n,r]of Object.entries(e.attributes))t.setAttribute(n,r);for(let[n,r]of Object.entries(e.morphAttributes)){let e=n;t.morphAttributes[e]=r.concat()}t.morphTargetsRelative=e.morphTargetsRelative,t.groups=[];for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t.boundingSphere=e.boundingSphere?.clone()??null,t.boundingBox=e.boundingBox?.clone()??null,t.drawRange.start=e.drawRange.start,t.drawRange.count=e.drawRange.count,t.userData=e.userData,t}function ev(e){if(Object.values(e).forEach(e=>{e?.isTexture&&e.dispose()}),e.isShaderMaterial){let t=e.uniforms;t&&Object.values(t).forEach(e=>{let t=e.value;t?.isTexture&&t.dispose()})}e.dispose()}function tv(e){let t=e.geometry;t&&t.dispose();let n=e.skeleton;n&&n.dispose();let r=e.material;r&&(Array.isArray(r)?r.forEach(e=>ev(e)):r&&ev(r))}function nv(e){e.traverse(tv)}function rv(e,t){console.warn(`VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.`);let n=t?.experimentalSameBoneCounts??!1,r=[];e.traverse(e=>{e.type===`SkinnedMesh`&&r.push(e)});let i=new Map,a=0;for(let e of r){let t=e.geometry.getAttribute(`skinIndex`);if(i.has(t))continue;let n=new Map,r=new Map;for(let e=0;e<t.count;e++)for(let i=0;i<t.itemSize;i++){let a=U_(t,e,i),o=n.get(a);o??(o=n.size,n.set(a,o),r.set(o,a)),W_(t,e,i,o)}t.needsUpdate=!0,i.set(t,r),a=Math.max(a,n.size)}for(let e of r){let t=e.geometry.getAttribute(`skinIndex`),r=i.get(t),o=[],s=[],c=n?a:r.size;for(let t=0;t<c;t++){let n=r.get(t)??0;o.push(e.skeleton.bones[n]),s.push(e.skeleton.boneInverses[n])}let l=new Yo(o,s);e.bind(l,new U)}}function iv(e,t){let n=e.position.count,r=Array(n),i=0,a=t.array;for(let e=0;e<a.length;e++){let t=a[e];r[t]||(r[t]=!0,i++)}return{isVertexUsed:r,vertexCount:n,verticesUsed:i}}function av(e){let t=[],n=[],r=0;for(let i=0;i<e.length;i++)if(e[i]){let e=r++;t[i]=e,n[e]=i}return{originalIndexNewIndexMap:t,newIndexOriginalIndexMap:n}}function ov(e,t){t.name=e.name,t.morphTargetsRelative=e.morphTargetsRelative,e.groups.forEach(e=>{t.addGroup(e.start,e.count,e.materialIndex)}),t.boundingBox=e.boundingBox?.clone()??null,t.boundingSphere=e.boundingSphere?.clone()??null,t.setDrawRange(e.drawRange.start,e.drawRange.count),t.userData=e.userData}function sv(e,t,n){let r=t.array,i=new r.constructor(r.length);for(let e=0;e<r.length;e++)i[e]=n[r[e]];e.setIndex(new G(i,t.itemSize,t.normalized))}function cv(e,t,n){let r=e.constructor,i=new r(t.length*n),a=!0;for(let r=0;r<t.length;r++){let o=t[r]*n,s=r*n;for(let t=0;t<n;t++){let n=e[o+t];i[s+t]=n,a&&=n===0}}return[i,a]}function lv(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e))if(i.isInterleavedBufferAttribute){let e=i,n=e.data,a=t.get(n)??[];t.set(n,a),a.push([r,e])}else{let e=i;n.push([r,e])}return[t,n]}function uv(e,t,n){let[r,i]=lv(t);for(let[t,i]of r){let r=t.array,{stride:a}=t,[o,s]=cv(r,n,a),c=new oo(o,a);c.setUsage(t.usage);for(let[t,n]of i){let{itemSize:r,offset:i,normalized:a}=n,o=new co(c,r,i,a);e.setAttribute(t,o)}}for(let[t,r]of i){let i=r.array,{itemSize:a,normalized:o}=r,[s,c]=cv(i,n,a);e.setAttribute(t,new G(s,a,o))}}function dv(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e)){let e=r;for(let r=0;r<i.length;r++){let a=i[r];if(a.isInterleavedBufferAttribute){let n=a,i=n.data,o=t.get(i)??[];t.set(i,o),o.push([e,r,n])}else{let t=a;n.push([e,r,t])}}}return[t,n]}function fv(e,t,n){let r=!0,[i,a]=dv(t),o={};for(let[e,t]of i){let i=e.array,{stride:a}=e,[s,c]=cv(i,n,a);r&&=c;let l=new oo(s,a);l.setUsage(e.usage);for(let[e,n,r]of t){let{itemSize:t,offset:i,normalized:a}=r,s=new co(l,t,i,a);o[e]??(o[e]=[]),o[e][n]=s}}for(let[e,t,i]of a){let a=i,s=a.array,{itemSize:c,normalized:l}=a,[u,d]=cv(s,n,c);r&&=d,o[e]??(o[e]=[]),o[e][t]=new G(u,c,l)}e.morphAttributes=r?{}:o}function pv(e){let t=new Map;e.traverse(e=>{if(!e.isMesh)return;let n=e,r=n.geometry,i=r.index;if(i==null)return;let a=t.get(r);if(a!=null){n.geometry=a;return}let{isVertexUsed:o,vertexCount:s,verticesUsed:c}=iv(r.attributes,i);if(c===s)return;let{originalIndexNewIndexMap:l,newIndexOriginalIndexMap:u}=av(o),d=new K;ov(r,d),t.set(r,d),sv(d,i,l),uv(d,r.attributes,u),fv(d,r.morphAttributes,u),n.geometry=d}),Array.from(t.keys()).forEach(e=>{e.dispose()})}function mv(e){e.meta?.metaVersion===`0`&&(e.scene.rotation.y=Math.PI)}var hv=class{constructor(){}};hv.combineMorphs=H_,hv.combineSkeletons=G_,hv.deepDispose=nv,hv.removeUnnecessaryJoints=rv,hv.removeUnnecessaryVertices=pv,hv.rotateVRM0=mv;function gv(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}function _v(e){let t=new Map,n=new Map,r=e.clone();return vv(e,r,function(e,r){t.set(r,e),n.set(e,r)}),r.traverse(function(e){if(!e.isSkinnedMesh)return;let r=e,i=t.get(e),a=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=a.map(function(e){return n.get(e)}),r.bind(r.skeleton,r.bindMatrix)}),r}function vv(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)vv(e.children[r],t.children[r],n)}var yv=class extends Ac{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new Tv(e)}),this.register(function(e){return new Ev(e)}),this.register(function(e){return new Fv(e)}),this.register(function(e){return new Iv(e)}),this.register(function(e){return new Lv(e)}),this.register(function(e){return new Ov(e)}),this.register(function(e){return new kv(e)}),this.register(function(e){return new Av(e)}),this.register(function(e){return new jv(e)}),this.register(function(e){return new wv(e)}),this.register(function(e){return new Mv(e)}),this.register(function(e){return new Dv(e)}),this.register(function(e){return new Pv(e)}),this.register(function(e){return new Nv(e)}),this.register(function(e){return new Sv(e)}),this.register(function(e){return new Rv(e,X.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new Rv(e,X.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new zv(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=al.extractUrlBase(e);a=al.resolveURL(t,this.path)}else a=al.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new Nc(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===Bv){try{a[X.KHR_BINARY_GLTF]=new Uv(e)}catch(e){r&&r(e);return}i=JSON.parse(a[X.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new hy(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case X.KHR_MATERIALS_UNLIT:a[t]=new Cv;break;case X.KHR_DRACO_MESH_COMPRESSION:a[t]=new Wv(i,this.dracoLoader);break;case X.KHR_TEXTURE_TRANSFORM:a[t]=new Gv;break;case X.KHR_MESH_QUANTIZATION:a[t]=new Kv;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function bv(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function xv(e,t,n){let r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}var X={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,KHR_MESHOPT_COMPRESSION:`KHR_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},Sv=class{constructor(e){this.parser=e,this.name=X.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new W(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],pr);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new rl(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new el(s),o.distance=c;break;case`spot`:o=new Qc(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),sy(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},Cv=class{constructor(){this.name=X.KHR_MATERIALS_UNLIT}getMaterialType(){return bo}extendParams(e,t,n){let r=[];e.color=new W(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],pr),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,fr))}return Promise.all(r)}},wv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}},Tv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatMap`,n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatRoughnessMap`,n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,`clearcoatNormalMap`,n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){let e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new z(e,e)}return Promise.all(r)}},Ev=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_DISPERSION}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion===void 0?0:n.dispersion),Promise.resolve()}},Dv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceMap`,n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceThicknessMap`,n.iridescenceThicknessTexture)),Promise.all(r)}},Ov=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_SHEEN}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(t.sheenColor=new W(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],pr)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenColorMap`,n.sheenColorTexture,fr)),n.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenRoughnessMap`,n.sheenRoughnessTexture)),Promise.all(r)}},kv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,`transmissionMap`,n.transmissionTexture)),Promise.all(r)}},Av=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_VOLUME}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.thickness=n.thicknessFactor===void 0?0:n.thicknessFactor,n.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`thicknessMap`,n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;let i=n.attenuationColor||[1,1,1];return t.attenuationColor=new W().setRGB(i[0],i[1],i[2],pr),Promise.all(r)}},jv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_IOR}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null?Promise.resolve():(t.ior=n.ior===void 0?1.5:n.ior,t.ior===0&&(t.ior=1e3),Promise.resolve())}},Mv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_SPECULAR}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.specularIntensity=n.specularFactor===void 0?1:n.specularFactor,n.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularIntensityMap`,n.specularTexture));let i=n.specularColorFactor||[1,1,1];return t.specularColor=new W().setRGB(i[0],i[1],i[2],pr),n.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularColorMap`,n.specularColorTexture,fr)),Promise.all(r)}},Nv=class{constructor(e){this.parser=e,this.name=X.EXT_MATERIALS_BUMP}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return t.bumpScale=n.bumpFactor===void 0?1:n.bumpFactor,n.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,`bumpMap`,n.bumpTexture)),Promise.all(r)}},Pv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,`anisotropyMap`,n.anisotropyTexture)),Promise.all(r)}},Fv=class{constructor(e){this.parser=e,this.name=X.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Iv=class{constructor(e){this.parser=e,this.name=X.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Lv=class{constructor(e){this.parser=e,this.name=X.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Rv=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},zv=class{constructor(e){this.name=X.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==Xv.TRIANGLES&&e.mode!==Xv.TRIANGLE_STRIP&&e.mode!==Xv.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new U,n=new V,a=new B,s=new V(1,1,1),c=new is(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new Xo(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Qi.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},Bv=`glTF`,Vv=12,Hv={JSON:1313821514,BIN:5130562},Uv=class{constructor(e){this.name=X.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Vv),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Bv)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-Vv,i=new DataView(e,Vv),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===Hv.JSON){let r=new Uint8Array(e,Vv+a,t);this.content=n.decode(r)}else if(r===Hv.BIN){let n=Vv+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},Wv=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=X.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=ty[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=ty[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=Zv[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,pr,n)})})}},Gv=class{constructor(){this.name=X.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},Kv=class{constructor(){this.name=X.KHR_MESH_QUANTIZATION}},qv=class extends dc{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},Jv=new B,Yv=class extends qv{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return Jv.fromArray(i).normalize().toArray(i),i}},Xv={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Zv={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Qv={9728:Bt,9729:Ut,9984:Vt,9985:Wt,9986:Ht,9987:Gt},$v={33071:Rt,33648:zt,10497:Lt},ey={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ty={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},ny={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},ry={CUBICSPLINE:void 0,LINEAR:nr,STEP:tr},iy={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function ay(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new rc({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function oy(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function sy(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function cy(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function ly(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function uy(e){let t,n=e.extensions&&e.extensions[X.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+dy(n.attributes):e.indices+`:`+dy(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+dy(e.targets[n]);return t}function dy(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function fy(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function py(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var my=new U,hy=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bv,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`&&navigator.userAgent!==void 0){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new Lc(this.options.manager):this.textureLoader=new sl(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Nc(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return oy(i,a,r),sy(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[X.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(al.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=ey[r.type],t=Zv[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new G(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=ey[r.type],o=Zv[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new oo(f,u/s),t.cache.add(n,c)),p=new co(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new G(f,a,d);if(r.sparse!==void 0){let t=ey.SCALAR,n=Zv[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new G(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=Qv[n.magFilter]||1006,t.minFilter=Qv[n.minFilter]||1008,t.wrapS=$v[n.wrapS]||1e3,t.wrapT=$v[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new bi(e);t.needsUpdate=!0,n(t)}),t.load(al.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),sy(e,a),e.userData.mimeType=a.mimeType||py(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[X.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[X.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[X.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new Ds,uo.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new ps,uo.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return rc}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[X.KHR_MATERIALS_UNLIT]){let e=r[X.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new W(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],pr),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,fr)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||iy.OPAQUE;if(l===iy.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===iy.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==bo&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new z(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==bo&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==bo){let e=i.emissiveFactor;o.emissive=new W().setRGB(e[0],e[1],e[2],pr)}return i.emissiveTexture!==void 0&&a!==bo&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,fr)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),sy(n,i),t.associations.set(n,{materials:e}),i.extensions&&oy(r,n,i),n})}createUniqueName(e){let t=wl.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[X.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return _y(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=uy(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[X.KHR_DRACO_MESH_COMPRESSION]?i(o):_y(new K,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?ay(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===Xv.TRIANGLES||u.mode===Xv.TRIANGLE_STRIP||u.mode===Xv.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new Wo(l,f):new Mo(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===Xv.TRIANGLE_STRIP?d.geometry=gv(d.geometry,1):u.mode===Xv.TRIANGLE_FAN&&(d.geometry=gv(d.geometry,2));else if(u.mode===Xv.LINES)d=new Ts(l,f);else if(u.mode===Xv.LINE_STRIP)d=new xs(l,f);else if(u.mode===Xv.LINE_LOOP)d=new Es(l,f);else if(u.mode===Xv.POINTS)d=new Ms(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&ly(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),sy(d,i),u.extensions&&oy(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&oy(r,c[0],i),c[0];let l=new $i;i.extensions&&oy(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new Xc(ri.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new tl(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),sy(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new U;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new Yo(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new wc(i,void 0,l);return sy(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,my)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);if(t.userData.pivot!==void 0&&n.length>0){let e=t.userData.pivot,r=n[0];t.pivot=new V().fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],r.position.set(0,0,0),delete t.userData.pivot}return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new Go:t.length>1?new $i:t.length===1?t[0]:new Qi,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),sy(o,i),i.extensions&&oy(n,o,i),i.matrix!==void 0){let e=new U;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new $i;n.name&&(i.name=r.createUniqueName(n.name)),sy(i,n),n.extensions&&oy(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++){let n=e[t];n.parent===null?i.add(n):i.add(_v(n))}return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof uo||e instanceof bi)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];function c(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}ny[i.path]===ny.weights?(c(e),e.isGroup&&e.children.forEach(c)):s.push(o);let l;switch(ny[i.path]){case ny.weights:l=yc;break;case ny.rotation:l=xc;break;case ny.translation:case ny.scale:l=Cc;break;default:switch(n.itemSize){case 1:l=yc;break;default:l=Cc;break}break}let u=r.interpolation===void 0?nr:ry[r.interpolation],d=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new l(s[e]+`.`+ny[i.path],t.array,d,u);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=fy(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof xc?Yv:qv)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function gy(e,t,n){let r=t.attributes,i=new Ca;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new V(t[0],t[1],t[2]),new V(a[0],a[1],a[2])),e.normalized){let t=fy(Zv[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new V,t=new V;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=fy(Zv[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Qa;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function _y(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=ty[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return ui.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ui.workingColorSpace}" not supported.`),sy(e,t),gy(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:cy(e,t.targets,n)})}var vy=class{models=new Map;animations=new Map;modelKeys=new Map;animationKeys=new Map;loader;constructor(){this.loader=new yv,this.loader.register(e=>new z_(e))}load(e){for(let[t,n]of Object.entries(e)){let e=n;typeof e.url==`string`&&(e.type===`model`?this.modelKeys.set(`$${t}`,e.url):e.type===`animation`&&this.animationKeys.set(`$${t}`,{url:e.url,clip:e.clip}))}}animationRefs(){return[...this.animationKeys.keys()]}modelRefs(){return[...this.modelKeys.keys()]}getModel(e){let t=this.modelKeys.get(e)??e,n=this.models.get(t);return n||(n={status:`loading`,scene:null,animations:[],isVrm:!1,vrm:null,claimedBy:null,retargeted:new Map},this.models.set(t,n),this.loader.load(t,e=>{let t=e.userData.vrm;t?(hv.removeUnnecessaryVertices(e.scene),hv.combineSkeletons(e.scene),hv.rotateVRM0(t),n.scene=t.scene,n.vrm=t,n.isVrm=!0):n.scene=e.scene,n.animations=e.animations??[],n.status=`ready`},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),console.error(`incanto: failed to load model '${t}':`,e)}),n)}getAnimation(e){let t=this.animationKeys.get(e)??{url:e},n=this.animations.get(t.url);return n||(n={status:`loading`,clips:[],scene:null,clip:t.clip},this.animations.set(t.url,n),this.loader.load(t.url,e=>{n.clips=e.animations??[],n.scene=e.scene,n.status=`ready`,n.clips.length===0&&console.warn(`incanto: animation asset '${t.url}' contains no clips`)},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),console.error(`incanto: failed to load animation '${t.url}':`,e)}),n)}dispose(){for(let e of this.models.values())e.scene?.traverse(e=>{let t=e;t.geometry?.dispose();let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)if(e){for(let t of Object.values(e))t?.isTexture&&t.dispose();e.dispose()}});this.models.clear(),this.animations.clear()}},yy=Math.atan(1/Math.SQRT2);function by(e,t,n,r,i,a){let o=[t[0],t[1]+n,t[2]];if(e===`firstPerson`)return{position:o,rotation:[-i,r,0]};if(e===`quarter`){let e=yy;return{position:[o[0],o[1]+a*Math.sin(e),o[2]+a*Math.cos(e)],rotation:[-e,0,0]}}if(e===`side`)return{position:[o[0],o[1],o[2]+a],rotation:[0,0,0]};let s=Math.cos(i);return{position:[o[0]+Math.sin(r)*s*a,o[1]+Math.sin(i)*a,o[2]+Math.cos(r)*s*a],rotation:[-i,r,0]}}function xy(e,t,n,r,i){let a=t[0]-e[0],o=t[1]-e[1],s=t[2]-e[2],c=Math.hypot(a,o,s);if(c<1e-4)return[t[0],t[1],t[2]];let l=[a/c,o/c,s/c],u=n(e,l,c);if(u===null)return[t[0],t[1],t[2]];let d=Math.min(c,Math.max(i,u-r));return[e[0]+l[0]*d,e[1]+l[1]*d,e[2]+l[2]*d]}function Sy(e,t,n){let r=t(e,n);return r===null||r>=n?[e[0],e[1],e[2]]:[e[0],e[1]+(n-r),e[2]]}function Cy(e,t,n){let r=Math.sin(n),i=Math.cos(n);return[e*i-t*r,0,-e*r-t*i]}function wy(e,t){return e?Math.min(.6+(t?.4:0),1):0}function Ty(e,t){return e?t<=0?`idle`:t<.3?`walk`:t<.7?`run`:`fastRun`:`airborne`}function Ey(e,t){let n=e.shape;if(n!==void 0){if(n===`box`){let n=e.size;if(!Array.isArray(n)||n.length!==3||n.some(e=>typeof e!=`number`))throw new y(`BAD_FORMAT`,`Collider on '${t}': box needs "size": [x, y, z].`);return}if(n===`sphere`){if(typeof e.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': sphere needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}if(n===`trimesh`){let n=e.vertices,r=e.indices;if(!Array.isArray(n)||n.length%3!=0||!Array.isArray(r)||r.length%3!=0)throw new y(`BAD_FORMAT`,`Collider on '${t}': trimesh needs "vertices" (flat xyz floats) and "indices" (triangle triplets).`);return}if(n!==`heightfield`)throw new y(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(n)}.`)}}var Dy=class extends Fe{static typeName=`Node3D`;static props={position:{default:[0,0,0]},rotation:{default:[0,0,0]},static:{default:!1},scale:{default:[1,1,1]},visible:{default:!0},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]}};position=[0,0,0];rotation=[0,0,0];static=!1;scale=[1,1,1];visible=!0;renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return rt(this.orderGroup,this.renderOrder)}_object3D=null;_interpPrev=null;_interpCurr=null;_ensureObject3D(){return this._object3D||(this._object3D=this._createObject3D(),this._object3D.userData.incantoNode=this),this._object3D}_createObject3D(){return new Qi}_syncObject3D(e=1){let t=this._ensureObject3D(),n=this._interpPrev,r=this._interpCurr;n&&r?t.position.set((n[0]??0)+((r[0]??0)-(n[0]??0))*e,(n[1]??0)+((r[1]??0)-(n[1]??0))*e,(n[2]??0)+((r[2]??0)-(n[2]??0))*e):t.position.set(this.position[0]??0,this.position[1]??0,this.position[2]??0),t.rotation.set(ri.degToRad(this.rotation[0]??0),ri.degToRad(this.rotation[1]??0),ri.degToRad(this.rotation[2]??0)),t.scale.set(this.scale[0]??1,this.scale[1]??1,this.scale[2]??1),t.visible=this.visible,t.renderOrder=this.effectiveRenderOrder}free(){super.free(),this._object3D?.removeFromParent(),this._object3D=null,this._interpPrev=null,this._interpCurr=null}},Oy=class extends Dy{static props={collider:{default:{}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){let t=e;if(Ey(t.collider,e.name),t.collider.shape===`heightfield`&&!(t instanceof ky))throw new y(`BAD_FORMAT`,`Collider on '${e.name}': heightfield is static terrain — put it on a StaticBody3D (with a Terrain3D child), not a ${t.constructor.typeName}.`,{prop:`collider`})}_physics=null},ky=class extends Oy{static typeName=`StaticBody3D`},Ay=class extends Oy{static typeName=`Area3D`},jy=class extends Oy{static typeName=`RigidBody3D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0,0];_physics3d=null;applyImpulse(e){this._physics3d?.applyImpulse(this,e)}},My=class extends Oy{static typeName=`CharacterBody3D`;static props={velocity:{default:[0,0,0]},snapToGround:{default:!0},slopeLimitDeg:{default:45}};velocity=[0,0,0];snapToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new y(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody3D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody3D '${this.name}' has no physics world — await enablePhysics3D(engine) first.`);this._physics.moveAndSlide(this)}isOnFloor(){return this._grounded}},Ny=class extends Dy{static typeName=`Joint3D`;static props={type:{default:`spherical`,options:[`fixed`,`spherical`,`rope`,`spring`]},target:{default:``},anchor:{default:[0,0,0]},targetAnchor:{default:[0,0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`spherical`;target=``;anchor=[0,0,0];targetAnchor=[0,0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof Oy))throw new y(`TREE_VIOLATION`,`Joint3D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new y(`BAD_FORMAT`,`Joint3D '${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 Oy))throw new y(`NODE_NOT_FOUND`,`Joint3D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Py=256,Fy=.3,Iy=.6,Ly=45;function Ry(e){let{width:t,depth:n,segsX:r,segsZ:i,maxHeight:a,seed:o}=e,s=e.roughness??.5,c=e.detail??4,l=e.flatThreshold??.95,u=e.islandEdge??!1,d=Math.max(0,Math.min(e.edgeWrapRadius??20,Ly)),f=e.edgeBottom??-50,p=e.edgeCornerSmoothness??1,m=(e.basins??[]).map(e=>({cx:e.x+t/2,cz:e.z+n/2,radius:e.radius,depth:e.depth})),h=tt(o),g=(e,t)=>(h(e,t)+1)*.5,_=(e,t)=>{let n=e/Py,r=t/Py,i=0,o=.2,u=5;for(let e=0;e<5;e++)i+=g(n*o,r*o)*u,u*=.5,o*=2;let d=0;o=.5,u=.1;for(let e=0;e<c;e++)d+=g(n*o,r*o)*u,u*=s,o*=2;i=Math.abs(i)**1.5*Math.sign(i),i<Fy&&(i*=.3);let f=a*(i+d*(i*.5+.5)+1)/2,p=a*l;if(Math.abs(f-p)<Iy&&(f=p),m.length>0){let n=0;for(let r of m){let i=Math.hypot(e-r.cx,t-r.cz);if(i<r.radius){let e=i/r.radius;n=Math.max(n,r.depth*(1-e*e*(3-2*e)))}}f-=n}return f},v=(e,a,o)=>{if(!u||d<=0)return o;let s=d,c=Math.min(e,t-e),l=Math.min(a,n-a),m=(t/r+n/i)*.002,h=Math.max(0,s-c+m),g=Math.max(0,s-l+m);if(h<=0&&g<=0)return o;let _=2+(1-Math.min(1,Math.max(0,p)))*30,v=(h**_+g**_)**(1/_),y=o-(s-Math.sqrt(Math.max(0,s*s-v*v)));return v>=s&&(y=Math.min(y,f)),y},y=r+1,b=i+1,x=new Float32Array(y*b),S=1/0,C=-1/0;for(let e=0;e<b;e++){let a=e/i*n;for(let n=0;n<y;n++){let i=n/r*t,o=_(i,a);o<S&&(S=o),o>C&&(C=o),x[e*y+n]=v(i,a,o)}}let w=(e,a)=>{let o=Math.min(Math.max((e+t/2)/t*r,0),r),s=Math.min(Math.max((a+n/2)/n*i,0),i),c=Math.min(Math.floor(o),r-1),l=Math.min(Math.floor(s),i-1),u=o-c,d=s-l,f=x[l*y+c],p=x[l*y+c+1],m=x[(l+1)*y+c],h=x[(l+1)*y+c+1];return(f*(1-u)+p*u)*(1-d)+(m*(1-u)+h*u)*d},T=(e,r)=>_(e+t/2,r+n/2);return{width:t,depth:n,segsX:r,segsZ:i,heights:x,minHeight:S,maxHeight:C,heightAt:w,baseHeight:T,slopeAt:(e,t)=>{let n=(T(e+1,t)-T(e-1,t))/2,r=(T(e,t+1)-T(e,t-1))/2;return Math.atan(Math.sqrt(n*n+r*r))}}}function zy(e,t,n,r){return e<t-r||e>n+r?0:e>=t&&e<=n?1:e<t?(e-(t-r))/r:(n+r-e)/r}function By(e,t,n,r=1.2){let i=[0,0,0,0],a=Math.min(n.length,4),o=0;for(let s=0;s<a;s++){let a=n[s],[c,l]=a.heightRange??[0,1],[u,d]=a.slopeRange??[0,Math.PI/2],f=zy(e,c,l,a.heightBlendRange??.1)*zy(t,u,d,a.slopeBlendRange??.1);f**=1/r,i[s]=f,o+=f}if(o===0)return[1,0,0,0];for(let e=0;e<4;e++)i[e]=i[e]/o;return i}function Vy(e,t,n){let r=e.indexOf(t);if(r===-1)throw new y(`BAD_FORMAT`,`Terrain3D shader patch: marker '${t}' not found in the three.js shader — the installed three version moved its chunks.`);let i=r+t.length;return`${e.slice(0,i)}\n${n}${e.slice(i)}`}var Hy=`
5037
+ `;e.vertexShader=t+e.vertexShader,e.fragmentShader=t+e.fragmentShader}}get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:184,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode===`normal`,DEBUG_LITSHADERATE:this._debugMode===`litShadeRate`,DEBUG_UV:this._debugMode===`uv`,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===ig.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}},sg=new Set([`1.0`,`1.0-beta`]),cg=class e{get name(){return e.EXTENSION_NAME}constructor(e,t={}){this.parser=e,this.materialType=t.materialType??og,this.renderOrderOffset=t.renderOrderOffset??0,this.v0CompatShade=t.v0CompatShade??!1,this.debugMode=t.debugMode??`none`,this._mToonMaterialSet=new Set}beforeRoot(){return Qh(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return Qh(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){let n=this._getMToonExtension(e);return n?this._extendMaterialParams(n,t):null}loadMesh(e){return Qh(this,null,function*(){let t=this.parser,n=t.json.meshes?.[e];if(n==null)throw Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let r=n.primitives,i=yield t.loadMesh(e);if(r.length===1){let e=i,t=r[0].material;t!=null&&this._setupPrimitive(e,t)}else{let e=i;for(let t=0;t<r.length;t++){let n=e.children[t],i=r[t].material;i!=null&&this._setupPrimitive(n,i)}}return i})}_removeUnlitExtensionIfMToonExists(){this.parser.json.materials?.map((e,t)=>{this._getMToonExtension(t)&&e.extensions?.KHR_materials_unlit&&delete e.extensions.KHR_materials_unlit})}_getMToonExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r==null)return;let i=r.specVersion;if(!sg.has(i)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${i}"`);return}return r}_extendMaterialParams(e,t){return Qh(this,null,function*(){delete t.metalness,delete t.roughness;let n=new eg(this.parser,t);n.assignPrimitive(`transparentWithZWrite`,e.transparentWithZWrite),n.assignColor(`shadeColorFactor`,e.shadeColorFactor),n.assignTexture(`shadeMultiplyTexture`,e.shadeMultiplyTexture,!0),n.assignPrimitive(`shadingShiftFactor`,e.shadingShiftFactor),n.assignTexture(`shadingShiftTexture`,e.shadingShiftTexture,!0),n.assignPrimitive(`shadingShiftTextureScale`,e.shadingShiftTexture?.scale),n.assignPrimitive(`shadingToonyFactor`,e.shadingToonyFactor),n.assignPrimitive(`giEqualizationFactor`,e.giEqualizationFactor),n.assignColor(`matcapFactor`,e.matcapFactor),n.assignTexture(`matcapTexture`,e.matcapTexture,!0),n.assignColor(`parametricRimColorFactor`,e.parametricRimColorFactor),n.assignTexture(`rimMultiplyTexture`,e.rimMultiplyTexture,!0),n.assignPrimitive(`rimLightingMixFactor`,e.rimLightingMixFactor),n.assignPrimitive(`parametricRimFresnelPowerFactor`,e.parametricRimFresnelPowerFactor),n.assignPrimitive(`parametricRimLiftFactor`,e.parametricRimLiftFactor),n.assignPrimitive(`outlineWidthMode`,e.outlineWidthMode),n.assignPrimitive(`outlineWidthFactor`,e.outlineWidthFactor),n.assignTexture(`outlineWidthMultiplyTexture`,e.outlineWidthMultiplyTexture,!1),n.assignColor(`outlineColorFactor`,e.outlineColorFactor),n.assignPrimitive(`outlineLightingMixFactor`,e.outlineLightingMixFactor),n.assignTexture(`uvAnimationMaskTexture`,e.uvAnimationMaskTexture,!1),n.assignPrimitive(`uvAnimationScrollXSpeedFactor`,e.uvAnimationScrollXSpeedFactor),n.assignPrimitive(`uvAnimationScrollYSpeedFactor`,e.uvAnimationScrollYSpeedFactor),n.assignPrimitive(`uvAnimationRotationSpeedFactor`,e.uvAnimationRotationSpeedFactor),n.assignPrimitive(`v0CompatShade`,this.v0CompatShade),n.assignPrimitive(`debugMode`,this.debugMode),yield n.pending})}_setupPrimitive(e,t){let n=this._getMToonExtension(t);if(n){e.renderOrder=this._parseRenderOrder(n)+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode==`string`&&e.outlineWidthMode!==`none`&&typeof e.outlineWidthFactor==`number`&&e.outlineWidthFactor>0}_generateOutline(e){let t=e.material;if(!(t instanceof uo)||!this._shouldGenerateOutline(t))return;e.material=[t];let n=t.clone();n.name+=` (Outline)`,n.isOutline=!0,n.side=1,e.material.push(n);let r=e.geometry,i=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,i,0),r.addGroup(0,i,1)}_addToMaterialSet(e){let t=e.material,n=new Set;Array.isArray(t)?t.forEach(e=>n.add(e)):n.add(t);for(let e of n)this._mToonMaterialSet.add(e)}_parseRenderOrder(e){return(e.transparentWithZWrite?0:19)+(e.renderQueueOffsetNumber??0)}};cg.EXTENSION_NAME=`VRMC_materials_mtoon`;var lg=cg,ug=(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())}),dg=class e{get name(){return e.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return ug(this,null,function*(){let n=this._getHDREmissiveMultiplierExtension(e);n!=null&&(console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead."),t.emissiveIntensity=n.emissiveMultiplier)})}_getHDREmissiveMultiplierExtension(t){let n=this.parser.json.materials?.[t];if(n==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${t}] of glTF but the material doesn't exist`);return}let r=n.extensions?.[e.EXTENSION_NAME];if(r!=null)return r}};dg.EXTENSION_NAME=`VRMC_materials_hdr_emissiveMultiplier`;var fg=dg,pg=Object.defineProperty,mg=Object.defineProperties,hg=Object.getOwnPropertyDescriptors,gg=Object.getOwnPropertySymbols,_g=Object.prototype.hasOwnProperty,vg=Object.prototype.propertyIsEnumerable,yg=(e,t,n)=>t in e?pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bg=(e,t)=>{for(var n in t||={})_g.call(t,n)&&yg(e,n,t[n]);if(gg)for(var n of gg(t))vg.call(t,n)&&yg(e,n,t[n]);return e},xg=(e,t)=>mg(e,hg(t)),Sg=(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 Cg(e){return e**2.2}var wg=class{get name(){return`VRMMaterialsV0CompatPlugin`}constructor(e){this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let t=this.parser.json;t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.indexOf(`KHR_texture_transform`)===-1&&t.extensionsUsed.push(`KHR_texture_transform`)}beforeRoot(){return Sg(this,null,function*(){let e=this.parser.json,t=e.extensions?.VRM?.materialProperties;t&&(this._populateRenderQueueMap(t),t.forEach((t,n)=>{let r=e.materials?.[n];if(r==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${n}] of glTF but the material doesn't exist`);return}if(t.shader===`VRM/MToon`){let i=this._parseV0MToonProperties(t,r);e.materials[n]=i}else if(t.shader?.startsWith(`VRM/Unlit`)){let i=this._parseV0UnlitProperties(t,r);e.materials[n]=i}else t.shader===`VRM_USE_GLTFSHADER`||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${t.shader}`)}))})}_parseV0MToonProperties(e,t){let n=e.keywordMap?._ALPHABLEND_ON??!1,r=e.floatProperties?._ZWrite===1&&n,i=this._v0ParseRenderQueue(e),a=e.keywordMap?._ALPHATEST_ON??!1,o=n?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=(e.floatProperties?._CullMode??2)===0,l=this._portTextureTransform(e),u=(e.vectorProperties?._Color??[1,1,1,1]).map((e,t)=>t===3?e:Cg(e)),d=e.textureProperties?._MainTex,f=d==null?void 0:{index:d,extensions:bg({},l)},p=e.floatProperties?._BumpScale??1,m=e.textureProperties?._BumpMap,h=m==null?void 0:{index:m,scale:p,extensions:bg({},l)},g=(e.vectorProperties?._EmissionColor??[0,0,0,1]).map(Cg),_=e.textureProperties?._EmissionMap,v=_==null?void 0:{index:_,extensions:bg({},l)},y=(e.vectorProperties?._ShadeColor??[.97,.81,.86,1]).map(Cg),b=e.textureProperties?._ShadeTexture,x=b==null?void 0:{index:b,extensions:bg({},l)},S=e.floatProperties?._ShadeShift??0,C=e.floatProperties?._ShadeToony??.9;C=ri.lerp(C,1,.5+.5*S),S=-S-(1-C);let w=e.floatProperties?._IndirectLightIntensity??.1,T=w?1-w:void 0,E=e.textureProperties?._SphereAdd,D=E==null?void 0:[1,1,1],O=E==null?void 0:{index:E},k=e.floatProperties?._RimLightingMix??0,A=e.textureProperties?._RimTexture,ee=A==null?void 0:{index:A,extensions:bg({},l)},te=(e.vectorProperties?._RimColor??[0,0,0,1]).map(Cg),ne=e.floatProperties?._RimFresnelPower??1,re=e.floatProperties?._RimLift??0,ie=[`none`,`worldCoordinates`,`screenCoordinates`][e.floatProperties?._OutlineWidthMode??0],ae=e.floatProperties?._OutlineWidth??0;ae=.01*ae;let oe=e.textureProperties?._OutlineWidthTexture,se=oe==null?void 0:{index:oe,extensions:bg({},l)},ce=(e.vectorProperties?._OutlineColor??[0,0,0]).map(Cg),le=(e.floatProperties?._OutlineColorMode??0)===1?e.floatProperties?._OutlineLightingMix??1:0,ue=e.textureProperties?._UvAnimMaskTexture,de=ue==null?void 0:{index:ue,extensions:bg({},l)},j=e.floatProperties?._UvAnimScrollX??0,fe=e.floatProperties?._UvAnimScrollY??0;fe!=null&&(fe=-fe);let pe=e.floatProperties?._UvAnimRotation??0,M={specVersion:`1.0`,transparentWithZWrite:r,renderQueueOffsetNumber:i,shadeColorFactor:y,shadeMultiplyTexture:x,shadingShiftFactor:S,shadingToonyFactor:C,giEqualizationFactor:T,matcapFactor:D,matcapTexture:O,rimLightingMixFactor:k,rimMultiplyTexture:ee,parametricRimColorFactor:te,parametricRimFresnelPowerFactor:ne,parametricRimLiftFactor:re,outlineWidthMode:ie,outlineWidthFactor:ae,outlineWidthMultiplyTexture:se,outlineColorFactor:ce,outlineLightingMixFactor:le,uvAnimationMaskTexture:de,uvAnimationScrollXSpeedFactor:j,uvAnimationScrollYSpeedFactor:fe,uvAnimationRotationSpeedFactor:pe};return xg(bg({},t),{pbrMetallicRoughness:{baseColorFactor:u,baseColorTexture:f},normalTexture:h,emissiveTexture:v,emissiveFactor:g,alphaMode:o,alphaCutoff:s,doubleSided:c,extensions:{VRMC_materials_mtoon:M}})}_parseV0UnlitProperties(e,t){let n=e.shader===`VRM/UnlitTransparentZWrite`,r=e.shader===`VRM/UnlitTransparent`||n,i=this._v0ParseRenderQueue(e),a=e.shader===`VRM/UnlitCutout`,o=r?`BLEND`:a?`MASK`:`OPAQUE`,s=a?e.floatProperties?._Cutoff??.5:void 0,c=this._portTextureTransform(e),l=(e.vectorProperties?._Color??[1,1,1,1]).map(Cg),u=e.textureProperties?._MainTex,d=u==null?void 0:{index:u,extensions:bg({},c)},f={specVersion:`1.0`,transparentWithZWrite:n,renderQueueOffsetNumber:i,shadeColorFactor:l,shadeMultiplyTexture:d};return xg(bg({},t),{pbrMetallicRoughness:{baseColorFactor:l,baseColorTexture:d},alphaMode:o,alphaCutoff:s,extensions:{VRMC_materials_mtoon:f}})}_portTextureTransform(e){let t=e.vectorProperties?._MainTex;if(t==null)return{};let n=[t?.[0]??0,t?.[1]??0],r=[t?.[2]??1,t?.[3]??1];return n[1]=1-r[1]-n[1],{KHR_texture_transform:{offset:n,scale:r}}}_v0ParseRenderQueue(e){let t=e.shader===`VRM/UnlitTransparentZWrite`,n=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||t,r=e.floatProperties?._ZWrite===1||t,i=0;if(n){let t=e.renderQueue;t!=null&&(i=r?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return i}_populateRenderQueueMap(e){let t=new Set,n=new Set;e.forEach(e=>{let r=e.shader===`VRM/UnlitTransparentZWrite`,i=e.keywordMap?._ALPHABLEND_ON!=null||e.shader===`VRM/UnlitTransparent`||r,a=e.floatProperties?._ZWrite===1||r;if(i){let r=e.renderQueue;r!=null&&(a?n.add(r):t.add(r))}}),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach((e,n)=>{let r=Math.min(Math.max(n-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,r)}),Array.from(n).sort().forEach((e,t)=>{let n=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,n)})}},Tg=(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())}),Eg=new V,Dg=class extends $i{constructor(e){super(),this._attrPosition=new G(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(vr);let t=new K;t.setAttribute(`position`,this._attrPosition);let n=new ps({color:16711935,depthTest:!1,depthWrite:!1});this._line=new xs(t,n),this.add(this._line),this.constraint=e}updateMatrixWorld(e){Eg.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Eg.x,Eg.y,Eg.z),this.constraint.source&&Eg.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Eg.x,Eg.y,Eg.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}};function Og(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}var kg=new V,Ag=new V;function jg(e,t){return e.decompose(kg,t,Ag),t}function Mg(e){return e.invert?e.invert():e.inverse(),e}var Ng=class{constructor(e,t){this.destination=e,this.source=t,this.weight=1}},Pg=new V,Fg=new V,Ig=new V,Lg=new B,Rg=new B,zg=new B,Bg=class extends Ng{get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set(e===`PositiveX`?1:e===`NegativeX`?-1:0,e===`PositiveY`?1:e===`NegativeY`?-1:0,e===`PositiveZ`?1:e===`NegativeZ`?-1:0)}get dependencies(){let e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}constructor(e,t){super(e,t),this._aimAxis=`PositiveX`,this._v3AimAxis=new V(1,0,0),this._dstRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let e=Lg.identity(),t=Rg.identity();this.destination.parent&&(jg(this.destination.parent.matrixWorld,e),Mg(t.copy(e)));let n=Pg.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),r=Og(this.source.matrixWorld,Fg).sub(Og(this.destination.matrixWorld,Ig)).normalize(),i=zg.setFromUnitVectors(n,r).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}};function Vg(e,t){let n=[e],r=e.parent;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}var Hg=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);t??(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e),this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.setInitState())}update(){let e=new Set,t=new Set;for(let n of this._constraints)this._processConstraint(n,e,t,e=>e.update())}_processConstraint(e,t,n,r){if(n.has(e))return;if(t.has(e))throw Error(`VRMNodeConstraintManager: Circular dependency detected while updating constraints`);t.add(e);let i=e.dependencies;for(let e of i)Vg(e,e=>{let i=this._objectConstraintsMap.get(e);if(i)for(let e of i)this._processConstraint(e,t,n,r)});r(e),n.add(e)}},Ug=new B,Wg=new B,Gg=class extends Ng{get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._dstRestQuat=new B,this._invSrcRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Mg(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let e=Ug.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=Wg.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}},Kg=new V,qg=new B,Jg=new B,Yg=class extends Ng{get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set(+(e===`X`),+(e===`Y`),+(e===`Z`))}get dependencies(){return new Set([this.source])}constructor(e,t){super(e,t),this._rollAxis=`X`,this._v3RollAxis=new V(1,0,0),this._dstRestQuat=new B,this._invDstRestQuat=new B,this._invSrcRestQuatMulDstRestQuat=new B}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Mg(this._invDstRestQuat.copy(this._dstRestQuat)),Mg(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let e=qg.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=Kg.copy(this._v3RollAxis).applyQuaternion(e),n=Jg.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(n,this.weight)}},Xg=new Set([`1.0`,`1.0-beta`]),Zg=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return Tg(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(t){return Tg(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let r=new Hg,i=yield this.parser.getDependencies(`node`);return i.forEach((t,a)=>{let o=n.nodes[a]?.extensions?.[e.EXTENSION_NAME];if(o==null)return;let s=o.specVersion;if(!Xg.has(s)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`);return}let c=o.constraint;if(c.roll!=null){let e=this._importRollConstraint(t,i,c.roll);r.addConstraint(e)}else if(c.aim!=null){let e=this._importAimConstraint(t,i,c.aim);r.addConstraint(e)}else if(c.rotation!=null){let e=this._importRotationConstraint(t,i,c.rotation);r.addConstraint(e)}}),t.scene.updateMatrixWorld(),r.setInitState(),r})}_importRollConstraint(e,t,n){let{source:r,rollAxis:i,weight:a}=n,o=t[r],s=new Yg(e,o);if(i!=null&&(s.rollAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new Dg(s);this.helperRoot.add(e)}return s}_importAimConstraint(e,t,n){let{source:r,aimAxis:i,weight:a}=n,o=t[r],s=new Bg(e,o);if(i!=null&&(s.aimAxis=i),a!=null&&(s.weight=a),this.helperRoot){let e=new Dg(s);this.helperRoot.add(e)}return s}_importRotationConstraint(e,t,n){let{source:r,weight:i}=n,a=t[r],o=new Gg(e,a);if(i!=null&&(o.weight=i),this.helperRoot){let e=new Dg(o);this.helperRoot.add(e)}return o}};Zg.EXTENSION_NAME=`VRMC_node_constraint`;var Qg=Zg,$g=(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())}),e_=class{},t_=new V,n_=new V,r_=class extends e_{get type(){return`capsule`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.tail=e?.tail??new V(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){t_.setFromMatrixPosition(e),n_.subVectors(this.tail,this.offset).applyMatrix4(e),n_.sub(t_);let i=n_.lengthSq();r.copy(t).sub(t_);let a=n_.dot(r);a<=0||(i<=a||n_.multiplyScalar(a/i),r.sub(n_));let o=r.length(),s=this.inside?this.radius-n-o:o-n-this.radius;return s<0&&(r.multiplyScalar(1/o),this.inside&&r.negate()),s}},i_=new V,a_=new H,o_=class extends e_{get type(){return`plane`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.normal=e?.normal??new V(0,0,1)}calculateCollision(e,t,n,r){r.setFromMatrixPosition(e),r.negate().add(t),a_.getNormalMatrix(e),i_.copy(this.normal).applyNormalMatrix(a_).normalize();let i=r.dot(i_)-n;return r.copy(i_),i}},s_=new V,c_=class extends e_{get type(){return`sphere`}constructor(e){super(),this.offset=e?.offset??new V(0,0,0),this.radius=e?.radius??0,this.inside=e?.inside??!1}calculateCollision(e,t,n,r){r.subVectors(t,s_.setFromMatrixPosition(e));let i=r.length(),a=this.inside?this.radius-n-i:i-n-this.radius;return a<0&&(r.multiplyScalar(1/i),this.inside&&r.negate()),a}},l_=new V,u_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new V,this._currentTail=new V,this._shape=e,this._attrPos=new G(new Float32Array(396),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);let n=l_.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),e=!0),e&&this._buildPosition()}_buildPosition(){l_.copy(this._currentTail).sub(this._currentOffset);let e=l_.length()/this._currentRadius;for(let t=0;t<=16;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(n),-Math.cos(n),0),this._attrPos.setXYZ(17+t,e+Math.sin(n),Math.cos(n),0),this._attrPos.setXYZ(34+t,-Math.sin(n),0,-Math.cos(n)),this._attrPos.setXYZ(51+t,e+Math.sin(n),0,Math.cos(n))}for(let t=0;t<32;t++){let n=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(n),Math.cos(n)),this._attrPos.setXYZ(100+t,e,Math.sin(n),Math.cos(n))}let t=Math.atan2(l_.y,Math.sqrt(l_.x*l_.x+l_.z*l_.z)),n=-Math.atan2(l_.z,l_.x);this.rotateZ(t),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){let t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}},d_=class extends K{constructor(e){super(),this.worldScale=1,this._currentOffset=new V,this._currentNormal=new V,this._shape=e,this._attrPos=new G(new Float32Array(18),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},f_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new V,this._shape=e,this._attrPos=new G(new Float32Array(288),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),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._currentOffset.x,this._currentOffset.y,this._currentOffset.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.needsUpdate=!0}},p_=new V,m_=class extends $i{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof c_)this._geometry=new f_(this.collider.shape);else if(this.collider.shape instanceof r_)this._geometry=new u_(this.collider.shape);else if(this.collider.shape instanceof o_)this._geometry=new d_(this.collider.shape);else throw Error(`VRMSpringBoneColliderHelper: Unknown collider shape type detected`);let t=new ps({color:16711935,depthTest:!1,depthWrite:!1});this._line=new Ts(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=p_.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},h_=class extends K{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new V,this._springBone=e,this._attrPos=new G(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new G(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1,t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),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}},g_=new V,__=class extends $i{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new h_(this.springBone);let t=new ps({color:16776960,depthTest:!1,depthWrite:!1});this._line=new Ts(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let t=this.matrix.elements;this._geometry.worldScale=g_.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}},v_=class extends Qi{constructor(e){super(),this.colliderMatrix=new U,this.shape=e}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),y_(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function y_(e,t,n){let r=t.elements;e.copy(t),n&&(e.elements[12]=r[0]*n.x+r[4]*n.y+r[8]*n.z+r[12],e.elements[13]=r[1]*n.x+r[5]*n.y+r[9]*n.z+r[13],e.elements[14]=r[2]*n.x+r[6]*n.y+r[10]*n.z+r[14])}var b_=new U;function x_(e){return e.invert?e.invert():e.getInverse(b_.copy(e)),e}var S_=class{constructor(e){this._inverseCache=new U,this._shouldUpdateInverse=!0,this.matrix=e;let t={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&=(x_(this._inverseCache.copy(this.matrix)),!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},C_=new U,w_=new V,T_=new V,E_=new V,D_=new V,O_=new U,k_=class{constructor(e,t,n={},r=[]){this._currentTail=new V,this._prevTail=new V,this._boneAxis=new V,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new U,this._initialLocalRotation=new B,this._initialLocalChildPosition=new V,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:n.hitRadius??0,stiffness:n.stiffness??1,gravityPower:n.gravityPower??0,gravityDir:n.gravityDir?.clone()??new V(0,-1,0),dragForce:n.dragForce??.4},this.colliderGroups=r}get dependencies(){let e=new Set,t=this.bone.parent;t&&e.add(t);for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++)e.add(this.colliderGroups[t].colliders[n]);return e}get center(){return this._center}set center(e){this._center?.userData.inverseCacheProxy&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new S_(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:C_}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);let e=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength();let t=T_.copy(this._boneAxis).transformDirection(this._initialLocalMatrix).transformDirection(this._parentMatrixWorld);D_.copy(this._currentTail).add(w_.subVectors(this._currentTail,this._prevTail).multiplyScalar(1-this.settings.dragForce)).applyMatrix4(this._getMatrixCenterToWorld()).addScaledVector(t,this.settings.stiffness*e).addScaledVector(this.settings.gravityDir,this.settings.gravityPower*e),E_.setFromMatrixPosition(this.bone.matrixWorld),D_.sub(E_).normalize().multiplyScalar(this._worldSpaceBoneLength).add(E_),this._collision(D_),this._prevTail.copy(this._currentTail),this._currentTail.copy(D_).applyMatrix4(this._getMatrixWorldToCenter());let n=O_.multiplyMatrices(this._parentMatrixWorld,this._initialLocalMatrix).invert();this.bone.quaternion.setFromUnitVectors(this._boneAxis,w_.copy(D_).applyMatrix4(n).normalize()).premultiply(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){for(let t=0;t<this.colliderGroups.length;t++)for(let n=0;n<this.colliderGroups[t].colliders.length;n++){let r=this.colliderGroups[t].colliders[n],i=r.shape.calculateCollision(r.colliderMatrix,e,this.settings.hitRadius,w_);if(i<0){e.addScaledVector(w_,-i),e.sub(E_);let t=e.length();e.multiplyScalar(this._worldSpaceBoneLength/t).add(E_)}}}_calcWorldSpaceBoneLength(){w_.setFromMatrixPosition(this.bone.matrixWorld),this.child?T_.setFromMatrixPosition(this.child.matrixWorld):(T_.copy(this._initialLocalChildPosition),T_.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=w_.sub(T_).length()}_getMatrixCenterToWorld(){return this._center?this._center.matrixWorld:C_}_getMatrixWorldToCenter(){return this._center?this._center.userData.inverseCacheProxy.inverse:C_}};function A_(e,t){let n=[],r=e;for(;r!==null;)n.unshift(r),r=r.parent;n.forEach(e=>{t(e)})}function j_(e,t){e.children.forEach(e=>{t(e)||j_(e,t)})}function M_(e){let t=new Map;for(let n of e){let r=n;do{let n=(t.get(r)??0)+1;if(n===e.size)return r;t.set(r,n),r=r.parent}while(r!==null)}return null}var N_=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn(`VRMSpringBoneManager: springBones is deprecated. use joints instead.`),this._joints}get colliderGroups(){let e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(t=>{e.add(t)})}),Array.from(e)}get colliders(){let e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(t=>{e.add(t)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t??(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e),this._isSortedJointsDirty=!0}addSpringBone(e){console.warn(`VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead.`),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e),this._isSortedJointsDirty=!0}deleteSpringBone(e){console.warn(`VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead.`),this.deleteJoint(e)}setInitState(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.setInitState()}}reset(){this._sortJoints();for(let e=0;e<this._sortedJoints.length;e++){let t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.reset()}}update(e){this._sortJoints();for(let e=0;e<this._ancestors.length;e++)this._ancestors[e].updateWorldMatrix(e===0,!1);for(let t=0;t<this._sortedJoints.length;t++){let n=this._sortedJoints[t];n.bone.updateMatrix(),n.bone.updateWorldMatrix(!1,!1),n.update(e),j_(n.bone,this._relevantChildrenUpdated)}}_sortJoints(){if(!this._isSortedJointsDirty)return;let e=[],t=new Set,n=new Set,r=new Set;for(let i of this._joints)this._insertJointSort(i,t,n,e,r);this._sortedJoints=e;let i=M_(r);this._ancestors=[],i&&(this._ancestors.push(i),j_(i,e=>(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(this._ancestors.push(e),!1))),this._isSortedJointsDirty=!1}_insertJointSort(e,t,n,r,i){if(n.has(e))return;if(t.has(e)){this._hasWarnedCircularDependency||=(console.warn(`VRMSpringBoneManager: Circular dependency detected`),!0);return}t.add(e);let a=e.dependencies;for(let e of a){let a=!1,o=null;A_(e,e=>{let s=this._objectSpringBonesMap.get(e);if(s)for(let e of s)a=!0,this._insertJointSort(e,t,n,r,i);else a||(o=e)}),o&&i.add(o)}r.push(e),n.add(e)}_relevantChildrenUpdated(e){return(this._objectSpringBonesMap.get(e)?.size??0)>0?!0:(e.updateWorldMatrix(!1,!1),!1)}},P_=`VRMC_springBone_extended_collider`,F_=new Set([`1.0`,`1.0-beta`]),I_=new Set([`1.0`]),L_=class e{get name(){return e.EXTENSION_NAME}constructor(e,t){this.parser=e,this.jointHelperRoot=t?.jointHelperRoot,this.colliderHelperRoot=t?.colliderHelperRoot,this.useExtendedColliders=t?.useExtendedColliders??!0}afterRoot(e){return $g(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return $g(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(t){return $g(this,null,function*(){var n;let r=t.parser.json;if(r.extensionsUsed?.indexOf(e.EXTENSION_NAME)===-1)return null;let i=new N_,a=yield t.parser.getDependencies(`node`),o=r.extensions?.[e.EXTENSION_NAME];if(!o)return null;let s=o.specVersion;if(!F_.has(s))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${e.EXTENSION_NAME} specVersion "${s}"`),null;let c=o.colliders?.map((t,n)=>{let r=a[t.node];if(r==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} attempted to reference a node #${t.node} but not found. Skipping the collider`),null;let i=t.shape,o=t.extensions?.[P_];if(this.useExtendedColliders&&o!=null){let t=o.specVersion;if(!I_.has(t))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${P_} specVersion "${t}". Fallbacking to the ${e.EXTENSION_NAME} definition`);else{let e=o.shape;if(e.sphere)return this._importSphereCollider(r,{offset:new V().fromArray(e.sphere.offset??[0,0,0]),radius:e.sphere.radius??0,inside:e.sphere.inside??!1});if(e.capsule)return this._importCapsuleCollider(r,{offset:new V().fromArray(e.capsule.offset??[0,0,0]),radius:e.capsule.radius??0,tail:new V().fromArray(e.capsule.tail??[0,0,0]),inside:e.capsule.inside??!1});if(e.plane)return this._importPlaneCollider(r,{offset:new V().fromArray(e.plane.offset??[0,0,0]),normal:new V().fromArray(e.plane.normal??[0,0,1])})}}if(i.sphere)return this._importSphereCollider(r,{offset:new V().fromArray(i.sphere.offset??[0,0,0]),radius:i.sphere.radius??0,inside:!1});if(i.capsule)return this._importCapsuleCollider(r,{offset:new V().fromArray(i.capsule.offset??[0,0,0]),radius:i.capsule.radius??0,tail:new V().fromArray(i.capsule.tail??[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${n} has no valid shape. Skipping the collider`)}),l=o.colliderGroups?.map((e,t)=>({colliders:(e.colliders??[]).map(e=>c?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a collider #${e} but not found. Skipping the collider`),null)).filter(e=>e!=null),name:e.name}));return(n=o.springs)==null||n.forEach((e,t)=>{let n=e.joints,r=e.colliderGroups?.map(e=>l?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null),o=e.center==null?void 0:a[e.center],s;n.forEach(e=>{if(s){let t=a[s.node],n=a[e.node],c={hitRadius:s.hitRadius,dragForce:s.dragForce,gravityPower:s.gravityPower,stiffness:s.stiffness,gravityDir:s.gravityDir==null?void 0:new V().fromArray(s.gravityDir)},l=this._importJoint(t,n,c,r);o&&(l.center=o),i.addJoint(l)}s=e})}),i.setInitState(),i})}_v0Import(e){return $g(this,null,function*(){let t=e.parser.json;if(t.extensionsUsed?.indexOf(`VRM`)===-1)return null;let n=t.extensions?.VRM?.secondaryAnimation;if(!n)return null;let r=n?.boneGroups;if(!r)return null;let i=new N_,a=yield e.parser.getDependencies(`node`),o=n.colliderGroups?.map((e,t)=>{let n=a[e.node];return n==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${t} attempted to reference a node #${e.node} but not found. Skipping the collider group`),null):{colliders:(e.colliders??[]).map((e,t)=>{let r=new V(0,0,0);return e.offset&&r.set(e.offset.x??0,e.offset.y??0,e.offset.z?-e.offset.z:0),this._importSphereCollider(n,{offset:r,radius:e.radius??0,inside:!1})})}});return r?.forEach((e,t)=>{let n=e.bones;n&&n.forEach(n=>{let r=a[n];if(r==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${t} attempted to reference a node #${n} but not found. Skipping the node`);return}let s=new V;e.gravityDir?s.set(e.gravityDir.x??0,e.gravityDir.y??0,e.gravityDir.z??0):s.set(0,-1,0);let c=e.center==null?void 0:a[e.center],l={hitRadius:e.hitRadius,dragForce:e.dragForce,gravityPower:e.gravityPower,stiffness:e.stiffiness,gravityDir:s},u=e.colliderGroups?.map(e=>o?.[e]??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${t} attempted to reference a collider group #${e} but not found. Skipping the collider group`),null)).filter(e=>e!=null);r.traverse(e=>{let t=e.children[0]??null,n=this._importJoint(e,t,l,u);c&&(n.center=c),i.addJoint(n)})})}),e.scene.updateMatrixWorld(),i.setInitState(),i})}_importJoint(e,t,n,r){let i=new k_(e,t,n,r);if(this.jointHelperRoot){let e=new __(i);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return i}_importSphereCollider(e,t){let n=new v_(new c_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importCapsuleCollider(e,t){let n=new v_(new r_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}_importPlaneCollider(e,t){let n=new v_(new o_(t));if(e.add(n),this.colliderHelperRoot){let e=new m_(n);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return n}};L_.EXTENSION_NAME=`VRMC_springBone`;var R_=L_,z_=class{get name(){return`VRMLoaderPlugin`}constructor(e,t){this.parser=e;let n=t?.helperRoot,r=t?.autoUpdateHumanBones;this.expressionPlugin=t?.expressionPlugin??new Fm(e),this.firstPersonPlugin=t?.firstPersonPlugin??new zm(e),this.humanoidPlugin=t?.humanoidPlugin??new ih(e,{helperRoot:n,autoUpdateHumanBones:r}),this.lookAtPlugin=t?.lookAtPlugin??new Bh(e,{helperRoot:n}),this.metaPlugin=t?.metaPlugin??new Uh(e),this.mtoonMaterialPlugin=t?.mtoonMaterialPlugin??new lg(e),this.materialsHDREmissiveMultiplierPlugin=t?.materialsHDREmissiveMultiplierPlugin??new fg(e),this.materialsV0CompatPlugin=t?.materialsV0CompatPlugin??new wg(e),this.springBonePlugin=t?.springBonePlugin??new R_(e,{colliderHelperRoot:n,jointHelperRoot:n}),this.nodeConstraintPlugin=t?.nodeConstraintPlugin??new Qg(e,{helperRoot:n})}beforeRoot(){return hm(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return hm(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){return this.mtoonMaterialPlugin.getMaterialType(e)??null}extendMaterialParams(e,t){return hm(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return hm(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let t=e.userData.vrmMeta,n=e.userData.vrmHumanoid;if(t&&n){let r=new Gh({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:n,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};function B_(e){let t=new Set;return e.traverse(e=>{if(!e.isMesh)return;let n=e;t.add(n)}),t}function V_(e,t,n){if(t.size===1){let n=t.values().next().value;if(n.weight===1)return e[n.index]}let r=new Float32Array(e[0].count*3),i=0;if(n)i=1;else for(let e of t)i+=e.weight;for(let n of t){let t=e[n.index],a=n.weight/i;for(let e=0;e<t.count;e++)r[e*3+0]+=t.getX(e)*a,r[e*3+1]+=t.getY(e)*a,r[e*3+2]+=t.getZ(e)*a}return new G(r,3)}function H_(e){let t=B_(e.scene),n=new Map,r=e.expressionManager?.expressionMap;if(r!=null)for(let[e,t]of Object.entries(r)){let r=new Set;for(let i of t.binds)if(i instanceof km){if(i.weight!==0)for(let t of i.primitives){let r=n.get(t);r??(r=new Map,n.set(t,r));let a=r.get(e);a??(a=new Set,r.set(e,a)),a.add(i)}r.add(i)}for(let e of r)t.deleteBind(e)}for(let e of t){let t=n.get(e);if(t==null)continue;let i=e.geometry.morphAttributes;e.geometry.morphAttributes={};let a=e.geometry.clone();e.geometry=a;let o=a.morphTargetsRelative,s=i.position!=null,c=i.normal!=null,l={},u={},d=[];if(s||c){s&&(l.position=[]),c&&(l.normal=[]);let n=0;for(let[a,f]of t)s&&(l.position[n]=V_(i.position,f,o)),c&&(l.normal[n]=V_(i.normal,f,o)),r?.[a].addBind(new km({index:n,weight:1,primitives:[e]})),u[a]=n,d.push(0),n++}a.morphAttributes=l,e.morphTargetDictionary=u,e.morphTargetInfluences=d}}function U_(e,t,n){if(e.getComponent)return e.getComponent(t,n);{let r=e.array[t*e.itemSize+n];return e.normalized&&(r=ri.denormalize(r,e.array)),r}}function W_(e,t,n,r){e.setComponent?e.setComponent(t,n,r):(e.normalized&&(r=ri.normalize(r,e.array)),e.array[t*e.itemSize+n]=r)}function G_(e){let t=K_(e),n=new Set;for(let e of t)n.has(e.geometry)&&(e.geometry=$_(e.geometry)),n.add(e.geometry);let r=new Map;for(let e of n){let t=e.getAttribute(`skinIndex`),n=r.get(t)??new Map;r.set(t,n);let i=e.getAttribute(`skinWeight`),a=q_(t,i);n.set(i,a)}let i=new Map;for(let e of t){let t=J_(e,r);i.set(e,t)}let a=[];for(let[e,t]of i){let n=!1;for(let r of a)if(Y_(t,r.boneInverseMap)){n=!0,r.meshes.add(e);for(let[e,n]of t)r.boneInverseMap.set(e,n);break}n||a.push({boneInverseMap:t,meshes:new Set([e])})}let o=new Map,s=new Q_,c=new Q_,l=new Q_;for(let e of a){let{boneInverseMap:t,meshes:n}=e,r=Array.from(t.keys()),i=new Yo(r,Array.from(t.values())),a=c.getOrCreate(i);for(let e of n){let t=e.geometry.getAttribute(`skinIndex`),n=s.getOrCreate(t),i=e.skeleton.bones,c=`${n};${a};${i.map(e=>l.getOrCreate(e)).join(`,`)}`,u=o.get(c);u??(u=t.clone(),X_(u,i,r),o.set(c,u)),e.geometry.setAttribute(`skinIndex`,u)}for(let e of n)e.bind(i,new U)}}function K_(e){let t=new Set;return e.traverse(e=>{if(!e.isSkinnedMesh)return;let n=e;t.add(n)}),t}function q_(e,t){let n=new Set;for(let r=0;r<e.count;r++)for(let i=0;i<e.itemSize;i++){let a=U_(e,r,i);U_(t,r,i)!==0&&n.add(a)}return n}function J_(e,t){let n=new Map,r=e.skeleton,i=e.geometry,a=i.getAttribute(`skinIndex`),o=i.getAttribute(`skinWeight`),s=t.get(a)?.get(o);if(!s)throw Error(`Unreachable. attributeUsedIndexSetMap does not know the skin index attribute or the skin weight attribute.`);for(let e of s)n.set(r.bones[e],r.boneInverses[e]);return n}function Y_(e,t){for(let[n,r]of e.entries()){let e=t.get(n);if(e!=null&&!Z_(r,e))return!1}return!0}function X_(e,t,n){let r=new Map;for(let e of t)r.set(e,r.size);let i=new Map;for(let[e,t]of n.entries()){let n=r.get(t);i.set(n,e)}for(let t=0;t<e.count;t++)for(let n=0;n<e.itemSize;n++){let r=U_(e,t,n),a=i.get(r);W_(e,t,n,a)}e.needsUpdate=!0}function Z_(e,t,n){if(n||=1e-4,e.elements.length!=t.elements.length)return!1;for(let r=0,i=e.elements.length;r<i;r++)if(Math.abs(e.elements[r]-t.elements[r])>n)return!1;return!0}var Q_=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(e){return this._objectIndexMap.get(e)}getOrCreate(e){let t=this._objectIndexMap.get(e);return t??(t=this._index,this._objectIndexMap.set(e,t),this._index++),t}};function $_(e){let t=new K;t.name=e.name,t.setIndex(e.index);for(let[n,r]of Object.entries(e.attributes))t.setAttribute(n,r);for(let[n,r]of Object.entries(e.morphAttributes)){let e=n;t.morphAttributes[e]=r.concat()}t.morphTargetsRelative=e.morphTargetsRelative,t.groups=[];for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t.boundingSphere=e.boundingSphere?.clone()??null,t.boundingBox=e.boundingBox?.clone()??null,t.drawRange.start=e.drawRange.start,t.drawRange.count=e.drawRange.count,t.userData=e.userData,t}function ev(e){if(Object.values(e).forEach(e=>{e?.isTexture&&e.dispose()}),e.isShaderMaterial){let t=e.uniforms;t&&Object.values(t).forEach(e=>{let t=e.value;t?.isTexture&&t.dispose()})}e.dispose()}function tv(e){let t=e.geometry;t&&t.dispose();let n=e.skeleton;n&&n.dispose();let r=e.material;r&&(Array.isArray(r)?r.forEach(e=>ev(e)):r&&ev(r))}function nv(e){e.traverse(tv)}function rv(e,t){console.warn(`VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.`);let n=t?.experimentalSameBoneCounts??!1,r=[];e.traverse(e=>{e.type===`SkinnedMesh`&&r.push(e)});let i=new Map,a=0;for(let e of r){let t=e.geometry.getAttribute(`skinIndex`);if(i.has(t))continue;let n=new Map,r=new Map;for(let e=0;e<t.count;e++)for(let i=0;i<t.itemSize;i++){let a=U_(t,e,i),o=n.get(a);o??(o=n.size,n.set(a,o),r.set(o,a)),W_(t,e,i,o)}t.needsUpdate=!0,i.set(t,r),a=Math.max(a,n.size)}for(let e of r){let t=e.geometry.getAttribute(`skinIndex`),r=i.get(t),o=[],s=[],c=n?a:r.size;for(let t=0;t<c;t++){let n=r.get(t)??0;o.push(e.skeleton.bones[n]),s.push(e.skeleton.boneInverses[n])}let l=new Yo(o,s);e.bind(l,new U)}}function iv(e,t){let n=e.position.count,r=Array(n),i=0,a=t.array;for(let e=0;e<a.length;e++){let t=a[e];r[t]||(r[t]=!0,i++)}return{isVertexUsed:r,vertexCount:n,verticesUsed:i}}function av(e){let t=[],n=[],r=0;for(let i=0;i<e.length;i++)if(e[i]){let e=r++;t[i]=e,n[e]=i}return{originalIndexNewIndexMap:t,newIndexOriginalIndexMap:n}}function ov(e,t){t.name=e.name,t.morphTargetsRelative=e.morphTargetsRelative,e.groups.forEach(e=>{t.addGroup(e.start,e.count,e.materialIndex)}),t.boundingBox=e.boundingBox?.clone()??null,t.boundingSphere=e.boundingSphere?.clone()??null,t.setDrawRange(e.drawRange.start,e.drawRange.count),t.userData=e.userData}function sv(e,t,n){let r=t.array,i=new r.constructor(r.length);for(let e=0;e<r.length;e++)i[e]=n[r[e]];e.setIndex(new G(i,t.itemSize,t.normalized))}function cv(e,t,n){let r=e.constructor,i=new r(t.length*n),a=!0;for(let r=0;r<t.length;r++){let o=t[r]*n,s=r*n;for(let t=0;t<n;t++){let n=e[o+t];i[s+t]=n,a&&=n===0}}return[i,a]}function lv(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e))if(i.isInterleavedBufferAttribute){let e=i,n=e.data,a=t.get(n)??[];t.set(n,a),a.push([r,e])}else{let e=i;n.push([r,e])}return[t,n]}function uv(e,t,n){let[r,i]=lv(t);for(let[t,i]of r){let r=t.array,{stride:a}=t,[o,s]=cv(r,n,a),c=new oo(o,a);c.setUsage(t.usage);for(let[t,n]of i){let{itemSize:r,offset:i,normalized:a}=n,o=new co(c,r,i,a);e.setAttribute(t,o)}}for(let[t,r]of i){let i=r.array,{itemSize:a,normalized:o}=r,[s,c]=cv(i,n,a);e.setAttribute(t,new G(s,a,o))}}function dv(e){let t=new Map,n=[];for(let[r,i]of Object.entries(e)){let e=r;for(let r=0;r<i.length;r++){let a=i[r];if(a.isInterleavedBufferAttribute){let n=a,i=n.data,o=t.get(i)??[];t.set(i,o),o.push([e,r,n])}else{let t=a;n.push([e,r,t])}}}return[t,n]}function fv(e,t,n){let r=!0,[i,a]=dv(t),o={};for(let[e,t]of i){let i=e.array,{stride:a}=e,[s,c]=cv(i,n,a);r&&=c;let l=new oo(s,a);l.setUsage(e.usage);for(let[e,n,r]of t){let{itemSize:t,offset:i,normalized:a}=r,s=new co(l,t,i,a);o[e]??(o[e]=[]),o[e][n]=s}}for(let[e,t,i]of a){let a=i,s=a.array,{itemSize:c,normalized:l}=a,[u,d]=cv(s,n,c);r&&=d,o[e]??(o[e]=[]),o[e][t]=new G(u,c,l)}e.morphAttributes=r?{}:o}function pv(e){let t=new Map;e.traverse(e=>{if(!e.isMesh)return;let n=e,r=n.geometry,i=r.index;if(i==null)return;let a=t.get(r);if(a!=null){n.geometry=a;return}let{isVertexUsed:o,vertexCount:s,verticesUsed:c}=iv(r.attributes,i);if(c===s)return;let{originalIndexNewIndexMap:l,newIndexOriginalIndexMap:u}=av(o),d=new K;ov(r,d),t.set(r,d),sv(d,i,l),uv(d,r.attributes,u),fv(d,r.morphAttributes,u),n.geometry=d}),Array.from(t.keys()).forEach(e=>{e.dispose()})}function mv(e){e.meta?.metaVersion===`0`&&(e.scene.rotation.y=Math.PI)}var hv=class{constructor(){}};hv.combineMorphs=H_,hv.combineSkeletons=G_,hv.deepDispose=nv,hv.removeUnnecessaryJoints=rv,hv.removeUnnecessaryVertices=pv,hv.rotateVRM0=mv;function gv(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}function _v(e){let t=new Map,n=new Map,r=e.clone();return vv(e,r,function(e,r){t.set(r,e),n.set(e,r)}),r.traverse(function(e){if(!e.isSkinnedMesh)return;let r=e,i=t.get(e),a=i.skeleton.bones;r.skeleton=i.skeleton.clone(),r.bindMatrix.copy(i.bindMatrix),r.skeleton.bones=a.map(function(e){return n.get(e)}),r.bind(r.skeleton,r.bindMatrix)}),r}function vv(e,t,n){n(e,t);for(let r=0;r<e.children.length;r++)vv(e.children[r],t.children[r],n)}var yv=class extends Ac{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new Tv(e)}),this.register(function(e){return new Ev(e)}),this.register(function(e){return new Fv(e)}),this.register(function(e){return new Iv(e)}),this.register(function(e){return new Lv(e)}),this.register(function(e){return new Ov(e)}),this.register(function(e){return new kv(e)}),this.register(function(e){return new Av(e)}),this.register(function(e){return new jv(e)}),this.register(function(e){return new wv(e)}),this.register(function(e){return new Mv(e)}),this.register(function(e){return new Dv(e)}),this.register(function(e){return new Pv(e)}),this.register(function(e){return new Nv(e)}),this.register(function(e){return new Sv(e)}),this.register(function(e){return new Rv(e,X.EXT_MESHOPT_COMPRESSION)}),this.register(function(e){return new Rv(e,X.KHR_MESHOPT_COMPRESSION)}),this.register(function(e){return new zv(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=al.extractUrlBase(e);a=al.resolveURL(t,this.path)}else a=al.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new Nc(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===Bv){try{a[X.KHR_BINARY_GLTF]=new Uv(e)}catch(e){r&&r(e);return}i=JSON.parse(a[X.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new hy(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case X.KHR_MATERIALS_UNLIT:a[t]=new Cv;break;case X.KHR_DRACO_MESH_COMPRESSION:a[t]=new Wv(i,this.dracoLoader);break;case X.KHR_TEXTURE_TRANSFORM:a[t]=new Gv;break;case X.KHR_MESH_QUANTIZATION:a[t]=new Kv;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function bv(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function xv(e,t,n){let r=e.json.materials[t];return r.extensions&&r.extensions[n]?r.extensions[n]:null}var X={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,KHR_MESHOPT_COMPRESSION:`KHR_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},Sv=class{constructor(e){this.parser=e,this.name=X.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new W(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],pr);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new rl(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new el(s),o.distance=c;break;case`spot`:o=new Qc(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),sy(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},Cv=class{constructor(){this.name=X.KHR_MATERIALS_UNLIT}getMaterialType(){return bo}extendParams(e,t,n){let r=[];e.color=new W(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],pr),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,fr))}return Promise.all(r)}},wv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}},Tv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatMap`,n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`clearcoatRoughnessMap`,n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,`clearcoatNormalMap`,n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){let e=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new z(e,e)}return Promise.all(r)}},Ev=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_DISPERSION}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion===void 0?0:n.dispersion),Promise.resolve()}},Dv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceMap`,n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`iridescenceThicknessMap`,n.iridescenceThicknessTexture)),Promise.all(r)}},Ov=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_SHEEN}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(t.sheenColor=new W(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let e=n.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],pr)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenColorMap`,n.sheenColorTexture,fr)),n.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,`sheenRoughnessMap`,n.sheenRoughnessTexture)),Promise.all(r)}},kv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,`transmissionMap`,n.transmissionTexture)),Promise.all(r)}},Av=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_VOLUME}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.thickness=n.thicknessFactor===void 0?0:n.thicknessFactor,n.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,`thicknessMap`,n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;let i=n.attenuationColor||[1,1,1];return t.attenuationColor=new W().setRGB(i[0],i[1],i[2],pr),Promise.all(r)}},jv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_IOR}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);return n===null?Promise.resolve():(t.ior=n.ior===void 0?1.5:n.ior,t.ior===0&&(t.ior=1e3),Promise.resolve())}},Mv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_SPECULAR}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.specularIntensity=n.specularFactor===void 0?1:n.specularFactor,n.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularIntensityMap`,n.specularTexture));let i=n.specularColorFactor||[1,1,1];return t.specularColor=new W().setRGB(i[0],i[1],i[2],pr),n.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,`specularColorMap`,n.specularColorTexture,fr)),Promise.all(r)}},Nv=class{constructor(e){this.parser=e,this.name=X.EXT_MATERIALS_BUMP}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return t.bumpScale=n.bumpFactor===void 0?1:n.bumpFactor,n.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,`bumpMap`,n.bumpTexture)),Promise.all(r)}},Pv=class{constructor(e){this.parser=e,this.name=X.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return xv(this.parser,e,this.name)===null?null:ic}extendMaterialParams(e,t){let n=xv(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,`anisotropyMap`,n.anisotropyTexture)),Promise.all(r)}},Fv=class{constructor(e){this.parser=e,this.name=X.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Iv=class{constructor(e){this.parser=e,this.name=X.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Lv=class{constructor(e){this.parser=e,this.name=X.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Rv=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},zv=class{constructor(e){this.name=X.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==Xv.TRIANGLES&&e.mode!==Xv.TRIANGLE_STRIP&&e.mode!==Xv.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new U,n=new V,a=new B,s=new V(1,1,1),c=new is(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new Xo(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);Qi.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},Bv=`glTF`,Vv=12,Hv={JSON:1313821514,BIN:5130562},Uv=class{constructor(e){this.name=X.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Vv),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Bv)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-Vv,i=new DataView(e,Vv),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===Hv.JSON){let r=new Uint8Array(e,Vv+a,t);this.content=n.decode(r)}else if(r===Hv.BIN){let n=Vv+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},Wv=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=X.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=ty[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=ty[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=Zv[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,pr,n)})})}},Gv=class{constructor(){this.name=X.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},Kv=class{constructor(){this.name=X.KHR_MESH_QUANTIZATION}},qv=class extends dc{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},Jv=new B,Yv=class extends qv{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return Jv.fromArray(i).normalize().toArray(i),i}},Xv={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Zv={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Qv={9728:Bt,9729:Ut,9984:Vt,9985:Wt,9986:Ht,9987:Gt},$v={33071:Rt,33648:zt,10497:Lt},ey={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ty={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},ny={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},ry={CUBICSPLINE:void 0,LINEAR:nr,STEP:tr},iy={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function ay(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new rc({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function oy(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function sy(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function cy(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function ly(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function uy(e){let t,n=e.extensions&&e.extensions[X.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+dy(n.attributes):e.indices+`:`+dy(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+dy(e.targets[n]);return t}function dy(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function fy(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function py(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var my=new U,hy=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new bv,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`&&navigator.userAgent!==void 0){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new Lc(this.options.manager):this.textureLoader=new sl(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Nc(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return oy(i,a,r),sy(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[X.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(al.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=ey[r.type],t=Zv[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new G(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=ey[r.type],o=Zv[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new oo(f,u/s),t.cache.add(n,c)),p=new co(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new G(f,a,d);if(r.sparse!==void 0){let t=ey.SCALAR,n=Zv[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new G(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=Qv[n.magFilter]||1006,t.minFilter=Qv[n.minFilter]||1008,t.wrapS=$v[n.wrapS]||1e3,t.wrapT=$v[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new bi(e);t.needsUpdate=!0,n(t)}),t.load(al.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),sy(e,a),e.userData.mimeType=a.mimeType||py(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[X.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[X.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[X.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new Ds,uo.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new ps,uo.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return rc}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[X.KHR_MATERIALS_UNLIT]){let e=r[X.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new W(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],pr),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,fr)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||iy.OPAQUE;if(l===iy.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===iy.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==bo&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new z(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==bo&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==bo){let e=i.emissiveFactor;o.emissive=new W().setRGB(e[0],e[1],e[2],pr)}return i.emissiveTexture!==void 0&&a!==bo&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,fr)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),sy(n,i),t.associations.set(n,{materials:e}),i.extensions&&oy(r,n,i),n})}createUniqueName(e){let t=wl.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[X.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return _y(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=uy(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[X.KHR_DRACO_MESH_COMPRESSION]?i(o):_y(new K,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?ay(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===Xv.TRIANGLES||u.mode===Xv.TRIANGLE_STRIP||u.mode===Xv.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new Wo(l,f):new Mo(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===Xv.TRIANGLE_STRIP?d.geometry=gv(d.geometry,1):u.mode===Xv.TRIANGLE_FAN&&(d.geometry=gv(d.geometry,2));else if(u.mode===Xv.LINES)d=new Ts(l,f);else if(u.mode===Xv.LINE_STRIP)d=new xs(l,f);else if(u.mode===Xv.LINE_LOOP)d=new Es(l,f);else if(u.mode===Xv.POINTS)d=new Ms(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&ly(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),sy(d,i),u.extensions&&oy(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&oy(r,c[0],i),c[0];let l=new $i;i.extensions&&oy(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new Xc(ri.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new tl(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),sy(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new U;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new Yo(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],a=e[1],o=e[2],s=e[3],c=e[4],l=[];for(let e=0,r=t.length;e<r;e++){let r=t[e],i=a[e],u=o[e],d=s[e],f=c[e];if(r===void 0)continue;r.updateMatrix&&r.updateMatrix();let p=n._createAnimationTracks(r,i,u,d,f);if(p)for(let e=0;e<p.length;e++)l.push(p[e])}let u=new wc(i,void 0,l);return sy(u,r),u})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,my)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);if(t.userData.pivot!==void 0&&n.length>0){let e=t.userData.pivot,r=n[0];t.pivot=new V().fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],r.position.set(0,0,0),delete t.userData.pivot}return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new Go:t.length>1?new $i:t.length===1?t[0]:new Qi,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),sy(o,i),i.extensions&&oy(n,o,i),i.matrix!==void 0){let e=new U;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);if(!r.associations.has(o))r.associations.set(o,{});else if(i.mesh!==void 0&&r.meshCache.refs[i.mesh]>1){let e=r.associations.get(o);r.associations.set(o,{...e})}return r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new $i;n.name&&(i.name=r.createUniqueName(n.name)),sy(i,n),n.extensions&&oy(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++){let n=e[t];n.parent===null?i.add(n):i.add(_v(n))}return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof uo||e instanceof bi)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];function c(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}ny[i.path]===ny.weights?(c(e),e.isGroup&&e.children.forEach(c)):s.push(o);let l;switch(ny[i.path]){case ny.weights:l=yc;break;case ny.rotation:l=xc;break;case ny.translation:case ny.scale:l=Cc;break;default:switch(n.itemSize){case 1:l=yc;break;default:l=Cc;break}break}let u=r.interpolation===void 0?nr:ry[r.interpolation],d=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new l(s[e]+`.`+ny[i.path],t.array,d,u);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=fy(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof xc?Yv:qv)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function gy(e,t,n){let r=t.attributes,i=new Ca;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new V(t[0],t[1],t[2]),new V(a[0],a[1],a[2])),e.normalized){let t=fy(Zv[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new V,t=new V;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=fy(Zv[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Qa;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function _y(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=ty[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return ui.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ui.workingColorSpace}" not supported.`),sy(e,t),gy(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:cy(e,t.targets,n)})}var vy=class{models=new Map;animations=new Map;modelKeys=new Map;animationKeys=new Map;loader;constructor(){this.loader=new yv,this.loader.register(e=>new z_(e))}load(e){for(let[t,n]of Object.entries(e)){let e=n;typeof e.url==`string`&&(e.type===`model`?this.modelKeys.set(`$${t}`,e.url):e.type===`animation`&&this.animationKeys.set(`$${t}`,{url:e.url,clip:e.clip}))}}animationRefs(){return[...this.animationKeys.keys()]}modelRefs(){return[...this.modelKeys.keys()]}getModel(e){let t=this.modelKeys.get(e)??e,n=this.models.get(t);return n||(n={status:`loading`,scene:null,animations:[],isVrm:!1,vrm:null,claimedBy:null,retargeted:new Map},this.models.set(t,n),this.loader.load(t,e=>{let t=e.userData.vrm;t?(hv.removeUnnecessaryVertices(e.scene),hv.combineSkeletons(e.scene),hv.rotateVRM0(t),n.scene=t.scene,n.vrm=t,n.isVrm=!0):n.scene=e.scene,n.animations=e.animations??[],n.status=`ready`},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),console.error(`incanto: failed to load model '${t}':`,e)}),n)}getAnimation(e){let t=this.animationKeys.get(e)??{url:e},n=this.animations.get(t.url);return n||(n={status:`loading`,clips:[],scene:null,clip:t.clip},this.animations.set(t.url,n),this.loader.load(t.url,e=>{n.clips=e.animations??[],n.scene=e.scene,n.status=`ready`,n.clips.length===0&&console.warn(`incanto: animation asset '${t.url}' contains no clips`)},void 0,e=>{n.status=`error`,n.error=e instanceof Error?e.message:String(e),console.error(`incanto: failed to load animation '${t.url}':`,e)}),n)}dispose(){for(let e of this.models.values())e.scene?.traverse(e=>{let t=e;t.geometry?.dispose();let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)if(e){for(let t of Object.values(e))t?.isTexture&&t.dispose();e.dispose()}});this.models.clear(),this.animations.clear()}},yy=Math.atan(1/Math.SQRT2);function by(e,t,n,r,i,a){let o=[t[0],t[1]+n,t[2]];if(e===`firstPerson`)return{position:o,rotation:[-i,r,0]};if(e===`quarter`){let e=yy;return{position:[o[0],o[1]+a*Math.sin(e),o[2]+a*Math.cos(e)],rotation:[-e,0,0]}}if(e===`side`)return{position:[o[0],o[1],o[2]+a],rotation:[0,0,0]};let s=Math.cos(i);return{position:[o[0]+Math.sin(r)*s*a,o[1]+Math.sin(i)*a,o[2]+Math.cos(r)*s*a],rotation:[-i,r,0]}}function xy(e,t,n,r,i){let a=t[0]-e[0],o=t[1]-e[1],s=t[2]-e[2],c=Math.hypot(a,o,s);if(c<1e-4)return[t[0],t[1],t[2]];let l=[a/c,o/c,s/c],u=n(e,l,c);if(u===null)return[t[0],t[1],t[2]];let d=Math.min(c,Math.max(i,u-r));return[e[0]+l[0]*d,e[1]+l[1]*d,e[2]+l[2]*d]}function Sy(e,t,n){let r=t(e,n);return r===null||r>=n?[e[0],e[1],e[2]]:[e[0],e[1]+(n-r),e[2]]}function Cy(e,t,n){let r=Math.sin(n),i=Math.cos(n);return[e*i-t*r,0,-e*r-t*i]}function wy(e,t){return e?Math.min(.6+(t?.4:0),1):0}function Ty(e,t){return e?t<=0?`idle`:t<.3?`walk`:t<.7?`run`:`fastRun`:`airborne`}function Ey(e,t){let n=e.shape;if(n!==void 0){if(n===`box`){let n=e.size;if(!Array.isArray(n)||n.length!==3||n.some(e=>typeof e!=`number`))throw new y(`BAD_FORMAT`,`Collider on '${t}': box needs "size": [x, y, z].`);return}if(n===`sphere`){if(typeof e.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': sphere needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}if(n===`trimesh`){let n=e.vertices,r=e.indices;if(!Array.isArray(n)||n.length%3!=0||!Array.isArray(r)||r.length%3!=0)throw new y(`BAD_FORMAT`,`Collider on '${t}': trimesh needs "vertices" (flat xyz floats) and "indices" (triangle triplets).`);return}if(n!==`heightfield`)throw new y(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(n)}.`)}}var Dy=class extends Fe{static typeName=`Node3D`;static props={position:{default:[0,0,0]},rotation:{default:[0,0,0]},static:{default:!1},scale:{default:[1,1,1]},visible:{default:!0},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]}};position=[0,0,0];rotation=[0,0,0];static=!1;scale=[1,1,1];visible=!0;renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return rt(this.orderGroup,this.renderOrder)}_object3D=null;_interpPrev=null;_interpCurr=null;_ensureObject3D(){return this._object3D||(this._object3D=this._createObject3D(),this._object3D.userData.incantoNode=this),this._object3D}_createObject3D(){return new Qi}_syncObject3D(e=1){let t=this._ensureObject3D(),n=this._interpPrev,r=this._interpCurr;n&&r?t.position.set((n[0]??0)+((r[0]??0)-(n[0]??0))*e,(n[1]??0)+((r[1]??0)-(n[1]??0))*e,(n[2]??0)+((r[2]??0)-(n[2]??0))*e):t.position.set(this.position[0]??0,this.position[1]??0,this.position[2]??0),t.rotation.set(ri.degToRad(this.rotation[0]??0),ri.degToRad(this.rotation[1]??0),ri.degToRad(this.rotation[2]??0)),t.scale.set(this.scale[0]??1,this.scale[1]??1,this.scale[2]??1),t.visible=this.visible,t.renderOrder=this.effectiveRenderOrder}free(){super.free(),this._object3D?.removeFromParent(),this._object3D=null,this._interpPrev=null,this._interpCurr=null}},Oy=class extends Dy{static props={collider:{default:{}}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;get collider(){return this._collider}set collider(e){this._collider=e,this._colliderChanged=!0}static validateJson(e){let t=e;if(Ey(t.collider,e.name),t.collider.shape===`heightfield`&&!(t instanceof ky))throw new y(`BAD_FORMAT`,`Collider on '${e.name}': heightfield is static terrain — put it on a StaticBody3D (with a Terrain3D child), not a ${t.constructor.typeName}.`,{prop:`collider`})}_physics=null},ky=class extends Oy{static typeName=`StaticBody3D`},Ay=class extends Oy{static typeName=`Area3D`},jy=class extends Oy{static typeName=`RigidBody3D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0,0]}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearVelocity=[0,0,0];_physics3d=null;applyImpulse(e){this._physics3d?.applyImpulse(this,e)}},My=class extends Oy{static typeName=`CharacterBody3D`;static props={velocity:{default:[0,0,0]},snapToGround:{default:!0},slopeLimitDeg:{default:45}};velocity=[0,0,0];snapToGround=!0;slopeLimitDeg=45;_grounded=!1;moveAndSlide(){if(!this._physics)throw new y(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody3D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody3D '${this.name}' has no physics world — await enablePhysics3D(engine) first.`);this._physics.moveAndSlide(this)}isOnFloor(){return this._grounded}},Ny=class extends Dy{static typeName=`Joint3D`;static props={type:{default:`spherical`,options:[`fixed`,`spherical`,`rope`,`spring`]},target:{default:``},anchor:{default:[0,0,0]},targetAnchor:{default:[0,0,0]},length:{default:0},stiffness:{default:50},damping:{default:5}};type=`spherical`;target=``;anchor=[0,0,0];targetAnchor=[0,0,0];length=0;stiffness=50;damping=5;onEnterTree(){if(!(this.parent instanceof Oy))throw new y(`TREE_VIOLATION`,`Joint3D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new y(`BAD_FORMAT`,`Joint3D '${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 Oy))throw new y(`NODE_NOT_FOUND`,`Joint3D '${this.name}': target '${this.target}' is not a physics body.`);return{a:e,b:t}}},Py=256,Fy=.3,Iy=.6,Ly=45;function Ry(e){let{width:t,depth:n,segsX:r,segsZ:i,maxHeight:a,seed:o}=e,s=e.roughness??.5,c=e.detail??4,l=e.flatThreshold??.95,u=e.islandEdge??!1,d=Math.max(0,Math.min(e.edgeWrapRadius??20,Ly)),f=e.edgeBottom??-50,p=e.edgeCornerSmoothness??1,m=(e.basins??[]).map(e=>({cx:e.x+t/2,cz:e.z+n/2,radius:e.radius,depth:e.depth})),h=tt(o),g=(e,t)=>(h(e,t)+1)*.5,_=(e,t)=>{let n=e/Py,r=t/Py,i=0,o=.2,u=5;for(let e=0;e<5;e++)i+=g(n*o,r*o)*u,u*=.5,o*=2;let d=0;o=.5,u=.1;for(let e=0;e<c;e++)d+=g(n*o,r*o)*u,u*=s,o*=2;i=Math.abs(i)**1.5*Math.sign(i),i<Fy&&(i*=.3);let f=a*(i+d*(i*.5+.5)+1)/2,p=a*l;if(Math.abs(f-p)<Iy&&(f=p),m.length>0){let n=0;for(let r of m){let i=Math.hypot(e-r.cx,t-r.cz);if(i<r.radius){let e=i/r.radius;n=Math.max(n,r.depth*(1-e*e*(3-2*e)))}}f-=n}return f},v=(e,a,o)=>{if(!u||d<=0)return o;let s=d,c=Math.min(e,t-e),l=Math.min(a,n-a),m=(t/r+n/i)*.002,h=Math.max(0,s-c+m),g=Math.max(0,s-l+m);if(h<=0&&g<=0)return o;let _=2+(1-Math.min(1,Math.max(0,p)))*30,v=(h**_+g**_)**(1/_),y=o-(s-Math.sqrt(Math.max(0,s*s-v*v)));return v>=s&&(y=Math.min(y,f)),y},y=r+1,b=i+1,x=new Float32Array(y*b),S=1/0,C=-1/0;for(let e=0;e<b;e++){let a=e/i*n;for(let n=0;n<y;n++){let i=n/r*t,o=_(i,a);o<S&&(S=o),o>C&&(C=o),x[e*y+n]=v(i,a,o)}}let w=(e,a)=>{let o=Math.min(Math.max((e+t/2)/t*r,0),r),s=Math.min(Math.max((a+n/2)/n*i,0),i),c=Math.min(Math.floor(o),r-1),l=Math.min(Math.floor(s),i-1),u=o-c,d=s-l,f=x[l*y+c],p=x[l*y+c+1],m=x[(l+1)*y+c],h=x[(l+1)*y+c+1];return(f*(1-u)+p*u)*(1-d)+(m*(1-u)+h*u)*d},T=(e,r)=>_(e+t/2,r+n/2);return{width:t,depth:n,segsX:r,segsZ:i,heights:x,minHeight:S,maxHeight:C,heightAt:w,baseHeight:T,slopeAt:(e,t)=>{let n=(T(e+1,t)-T(e-1,t))/2,r=(T(e,t+1)-T(e,t-1))/2;return Math.atan(Math.sqrt(n*n+r*r))}}}function zy(e,t,n,r){return e<t-r||e>n+r?0:e>=t&&e<=n?1:e<t?(e-(t-r))/r:(n+r-e)/r}function By(e,t,n,r=1.2){let i=[0,0,0,0],a=Math.min(n.length,4),o=0;for(let s=0;s<a;s++){let a=n[s],[c,l]=a.heightRange??[0,1],[u,d]=a.slopeRange??[0,Math.PI/2],f=zy(e,c,l,a.heightBlendRange??.1)*zy(t,u,d,a.slopeBlendRange??.1);f**=1/r,i[s]=f,o+=f}if(o===0)return[1,0,0,0];for(let e=0;e<4;e++)i[e]=i[e]/o;return i}function Vy(e,t,n){let r=e.indexOf(t);if(r===-1)throw new y(`BAD_FORMAT`,`Terrain3D shader patch: marker '${t}' not found in the three.js shader — the installed three version moved its chunks.`);let i=r+t.length;return`${e.slice(0,i)}\n${n}${e.slice(i)}`}var Hy=`
5038
5038
  varying vec3 vSplatColor;
5039
5039
  varying vec3 vWorldPosition;
5040
5040
  varying vec2 vUvSplat;
@@ -5298,7 +5298,7 @@ if (splatDetailAmount > 0.001) {
5298
5298
 
5299
5299
  normal = perturbSplatNormal(normal, vViewPosition, vUvSplat, blendedNormalSample);
5300
5300
  #endif
5301
- `;function Xy(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.splatEnvCut={value:t.envCut},e.vertexShader=Vy(e.vertexShader,`#include <common>`,Hy),e.vertexShader=Vy(e.vertexShader,`#include <begin_vertex>`,Uy);let n=e.fragmentShader;n=Vy(n,`#include <common>`,Wy),n=Vy(n,`#include <color_fragment>`,Gy),n=Vy(n,`#include <roughnessmap_fragment>`,Ky),n=Vy(n,`#include <metalnessmap_fragment>`,Jy),n=Vy(n,`#include <normal_fragment_maps>`,Yy),n=Vy(n,`#include <lights_fragment_maps>`,qy),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var Zy=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],Qy=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,$y=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,eb=1/3,tb=Math.PI/4;function nb(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function rb(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[nb(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),nb(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),nb(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[nb(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),nb(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),nb(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),nb(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),nb(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),nb(n,`gravel`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[nb(n,`sand`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${$y}/grass.jpg`,heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:eb,uvNoiseIntensity:0},{texture:`${$y}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:eb,uvNoiseIntensity:0}]:[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${$y}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:eb,uvNoiseIntensity:0},{texture:`${$y}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:eb,uvNoiseIntensity:0}]:[nb(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),nb(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[nb(n,`snow`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[nb(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),nb(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var ib={scale:100,threshold:.7,blend:.1},ab={scale:55,threshold:.58,blend:.12},ob={scale:85,threshold:.62,blend:.12},sb={scale:48,threshold:.5,blend:.14};function cb(e,t){let n=tt(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 lb(e,t){return e===`grassland`?cb(t,ib):e===`forest`?cb(t,ab):e===`savanna`?cb(t,ob):e===`wetland`?cb(t,sb):null}function ub(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var db=128,fb=class extends Dy{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:Zy},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:Qy},basins:{default:[]}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=Qy;basins=[];static validateJson(e){let t=e;if(!Zy.includes(t.theme))throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${Zy.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:Zy});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new y(`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 y(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>db)throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${db}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new y(`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 y(`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 y(`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 y(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});if(!Array.isArray(t.basins))throw new y(`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)||!(t.depth>0))throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z and positive radius, depth, got ${JSON.stringify(t)}.`,{prop:`basins`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new y(`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)=>{hb(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new y(`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=``;loadedTextures=[];_createObject3D(){let e=new K;return e.setAttribute(`position`,new G(new Float32Array,3)),new Mo(e,new rc({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Dy&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_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]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=Ry({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}),this.heightmapKey=t),this.heightmap}resolvedLayers(){return this.theme===`custom`?this.layers:rb(this.theme,this.textureBase)}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded()}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),db))}rebuildIfNeeded(){let e=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]);if(e===this.builtKey)return;this.builtKey=e;let t=this._ensureObject3D();t.geometry.dispose(),t.geometry=this.buildGeometry(),t.material.dispose(),this.disposeTextures(),t.material=this.buildMaterial(),t.receiveShadow=!0,t.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new Gs(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:ub(this.theme),s=o?lb(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=By(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 G(a,3)),t}buildMaterial(){let e=this.resolvedLayers(),t=new rc({vertexColors:!0}),n=typeof document<`u`?new Lc:null,r=(e,t)=>{if(!n||!e)return null;let r=n.load(e);return r.wrapS=Lt,r.wrapT=Lt,r.anisotropy=8,t&&(r.colorSpace=fr),this.loadedTextures.push(r),r},i=e.map(e=>r(e.texture,!0)),a=e.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]=mb());let s={textures:i,normalMaps:a,repeats:e.map(e=>e.repeat??2),roughness:e.map(e=>e.roughness??1),metalness:e.map(e=>e.metalness??0),uvNoiseIntensity:e.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,e.length),hasNormalMaps:o};return t.onBeforeCompile=e=>{Xy(e,s)},t.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,t}disposeTextures(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[]}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.disposeTextures(),this.heightmap=null,super.free()}},pb=null;function mb(){return pb||(pb=new Ko(new Uint8Array([128,128,255,255]),1,1),pb.needsUpdate=!0),pb}function hb(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new y(`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 y(`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 y(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var gb=Math.PI/180;async function _b(e,t){let n=await mp(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await n.init(),new vb(n,e,t)}var vb=class{R;engine;debugDraw=!1;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.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=cp(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}step(e){if(this.lastDt=e,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]=Eb(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 jy){if(!e.fixedRotation){let n=t.body.rotation();bb.setFromQuaternion(yb.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=bb.x/gb,r[1]=bb.y/gb,r[2]=bb.z/gb}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=wb(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`;r.emit(a,i),i.emit(a,r)})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.snapToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*gb);let r={x:(e.velocity[0]??0)*this.lastDt,y:n*this.lastDt,z:(e.velocity[2]??0)*this.lastDt};this.kcc.computeColliderMovement(t.collider,r,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let i=this.kcc.computedMovement(),a=t.body.translation();t.body.setNextKinematicTranslation({x:a.x+i.x,y:a.y+i.y,z:a.z+i.z}),e._grounded=this.kcc.computedGrounded()}debugLines(){return this.debugDraw?this.world.debugRender().vertices:null}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=t!==this.lastStructure||e.root!==this.lastRoot;n&&(this.lastStructure=t,this.lastRoot=e.root,this.bodySet.clear(),Sb(e.root,this.bodySet)),n&&(this.jointSet.clear(),xb(e.root,this.jointSet));let r=this.bodySet;for(let e of r){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),console.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(n),n)for(let[e,t]of this.entries)r.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;r=e instanceof jy?n.RigidBodyDesc.dynamic():e instanceof My||e instanceof Ay?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[i,a,o]=wb(e);r.setTranslation(i,a,o),yb.setFromEuler(bb.set((e.rotation[0]??0)*gb,(e.rotation[1]??0)*gb,(e.rotation[2]??0)*gb,`XYZ`)),r.setRotation({x:yb.x,y:yb.y,z:yb.z,w:yb.w}),e instanceof jy&&(r.setGravityScale(e.gravityScale),r.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&r.lockRotations());let s=this.world.createRigidBody(r),c=Db(n,e);c.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),c.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof Ay&&c.setSensor(!0),e instanceof jy&&c.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(c,s);return t={body:s,collider:l,last:[i,a,o],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e._colliderChanged=!1,e._physics=this,e instanceof jy&&(e._physics3d=this),t}let r=wb(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 jy){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}},yb=new B,bb=new Fi;function xb(e,t){e instanceof Ny&&t.add(e);for(let n of e.children)xb(n,t)}function Sb(e,t){e instanceof Oy&&t.add(e);for(let n of e.children)Sb(n,t)}var Cb=[0,0,0];function wb(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return Cb[0]=t,Cb[1]=n,Cb[2]=r,Cb}var Tb=[0,0,0];function Eb(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return Tb[0]=t,Tb[1]=n,Tb[2]=r,Tb}function Db(e,t){let n=t.collider;if(Ey(n,t.name),n.shape===`heightfield`)return Ob(e,t);let r=kb(e,n,t.name),i=n.offset;return Array.isArray(i)&&r.setTranslation(i[0]??0,i[1]??0,i[2]??0),r}function Ob(e,t){let n=t.children.find(e=>e instanceof fb);if(!n)throw new y(`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 kb(e,t,n){let r=t.shape;if(r===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new y(`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(r===`sphere`){if(typeof t.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2,t.radius)}if(r===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new y(`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 y(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(r)}.`)}var Ab=new Gs(1,1),jb=null;function Mb(){if(jb)return jb;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),jb=new Fs(e),jb}var Nb=new V(0,0,1),Pb=new V,Fb=new V,Ib=new B,Lb=new B,Rb=new V,zb=.5,Bb=class extends Dy{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 Mo(Ab,new bo({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(){if(!this.texture)return null;if(this.textureRef!==this.texture&&(this.loadedTexture?.dispose(),this.loadedTexture=null,this.textureRef=this.texture,typeof document<`u`)){let e=new Lc().load(this.texture);e.colorSpace=fr;let t=this.pixelArt?Bt:Ut;e.magFilter=t,e.minFilter=t,this.loadedTexture=e}return this.loadedTexture}_syncObject3D(e=1){super._syncObject3D(e);let t=this._quad(),n=t.material,r=this.size[0]??1,i=this.size[1]??1;t.scale.set(this.flipX?-r:r,i,1);let a=this.anchor[0]??.5,o=this.anchor[1]??0;t.position.set((.5-a)*r,(.5-o)*i,0);let s=this.resolveTexture();n.map!==s&&(n.map=s,n.needsUpdate=!0),t.visible=s!==null,n.color.set(this.tint),n.opacity=this.opacity,n.transparent=this.opacity<1,n.alphaTest=this.alphaTest,t.renderOrder=this.renderOrder;let c=this.castShadow&&s!==null;if(t.castShadow=!1,c&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-r:r,i,1),e.position.set((.5-a)*r,(.5-o)*i,0);let t=e.material;t.map!==s&&(t.map=s,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==s&&(n.map=s,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(c&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(r*.52,r*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new Mo(Ab,new bo({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new ac({depthPacking:dr,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new Mo(Ab,new bo({map:Mb(),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(Fb),Fb.y=0,Fb.lengthSq()>=1e-6&&this._faceDir(this._quad(),Fb.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(Lb),Rb.copy(e.sunDir).applyQuaternion(Lb.invert()),t.position.addScaledVector(Rb,zb))}_faceToward(e,t){e.getWorldPosition(Pb),Fb.copy(t).sub(Pb),this.billboard===`y`&&(Fb.y=0),!(Fb.lengthSq()<1e-12)&&(Fb.normalize(),Ib.setFromUnitVectors(Nb,Fb),e.parent?.getWorldQuaternion(Lb),e.quaternion.copy(Lb.invert()).multiply(Ib))}_faceDir(e,t){Fb.copy(t),this.billboard===`y`&&(Fb.y=0),!(Fb.lengthSq()<1e-12)&&(Fb.normalize(),Ib.setFromUnitVectors(Nb,Fb),e.parent?.getWorldQuaternion(Lb),e.quaternion.copy(Lb.invert()).multiply(Ib))}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()}},Vb=class extends Bb{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 y(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=Hb(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(){if(!this.sheet||this.frameWidth<=0||this.frameHeight<=0)return null;if(this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.sheetTexture=null,this.loadedSheetRef=this.sheet,typeof document<`u`)){let e=new Lc().load(this.sheet);e.colorSpace=fr;let t=this.pixelArt?Bt:Ut;e.magFilter=t,e.minFilter=t,this.sheetTexture=e}let e=this.sheetTexture;if(!e)return null;let t=e.image;if(!t?.width||!t.height)return e;let n=Math.max(1,Math.floor(t.width/this.frameWidth)),r=this.currentFrame%n,i=Math.floor(this.currentFrame/n);return e.repeat.set(this.frameWidth/t.width,this.frameHeight/t.height),e.offset.set(r*this.frameWidth/t.width,1-(i+1)*this.frameHeight/t.height),e}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}};function Hb(e,t){if(!Array.isArray(e)||e.length===0)throw new y(`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 Ub=new B,Wb=new B,Gb=new V,Kb=new V(0,0,1),qb=[`screen`,`y`,`none`],Jb=class extends Dy{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:qb}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!qb.includes(t.mode))throw new y(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${qb.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:qb})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(Wb);else if(e.camera.getWorldDirection(Gb),Gb.y=0,Gb.lengthSq()>=1e-6)Wb.setFromUnitVectors(Kb,Gb.negate().normalize());else if(this._lastDesired)Wb.copy(this._lastDesired);else return;this._lastDesired||=new B,this._lastDesired.copy(Wb),t.parent?.getWorldQuaternion(Ub),t.parent?t.quaternion.copy(Ub.invert()).multiply(Wb):t.quaternion.copy(Wb)}},Yb=class extends Dy{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 Xc(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())}},Xb=8,Zb=.2,Qb=.15,$b=1.2,ex=.08,tx=2.5,nx=-20,rx=.002,ix=180/Math.PI,ax=.3,ox=.4,sx=.3,cx=new Fi,lx=new B,ux=new U,dx=new V,fx=new V,px=new V(0,1,0),mx=class extends Dy{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`},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 jy))throw new y(`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=gx(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]:Cy(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;p=n[0]/i,m=n[2]/i}catch{}let g=_x(r,this.sprintAction),_=wy(h,g),v=1+(this.sprintMultiplier-1)*_,y=h?this.maxSpeed*v:0,b=this.grounded?1:Zb,x=(p*y-s[0])/Xb*b,S=(m*y-s[2])/Xb*b;if(t.applyImpulse([x*c,0,S*c]),!h&&this.grounded&&t.applyImpulse([-s[0]*Qb*c,0,-s[2]*Qb*c]),f!==null&&f<l*2){let e=$b*(l-f)-s[1]*ex;t.applyImpulse([0,e*c,0])}if(this.grounded&&_x(r,this.jumpAction)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*_);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1}s[1]<nx?t.gravityScale=0:s[1]<0&&!this.grounded?t.gravityScale=tx:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let C=Ty(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)*ix+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*ix;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*rx,this.pitch=hx(this.pitch+e.y*rx,-this.pitchMax,-this.pitchMin);let n=t.wheelDelta();n!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=hx(this.camDistance+n*rx,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof jy?this.parent:null;if(!r)return;let i=gx(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=by(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=xy(l,u,(t,n,i)=>e.castRay(t,n,i,r,{staticOnly:!0})?.distance??null,ax,ox),u=Sy(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,sx))}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`?(dx.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),fx.set(l[0],l[1],l[2]),ux.lookAt(dx,fx,px),lx.setFromRotationMatrix(ux),cx.setFromQuaternion(lx,`XYZ`)):(cx.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),lx.setFromEuler(cx),cx.setFromQuaternion(lx,`XYZ`)),n.rotation=[cx.x*ix,cx.y*ix,cx.z*ix]}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 Yb&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function hx(e,t,n){return Math.min(n,Math.max(t,e))}function gx(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Dy;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}function _x(e,t){try{return e.isPressed(t)}catch{return!1}}var vx=.15,yx=.7,bx=.5,xx=.7,Sx=.5;function Cx(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 wx(e,t){let n=Cx(e*vx,t*vx,4),r=Cx(e*vx*.2,t*vx*.2,2);return n>bx-yx*.5-r*Sx}var Tx=.9;function Ex(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 Dx(e,t,n=Tx){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+Ex(u,d,0))*n,p=(d+Ex(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:Ex(o,s,2)*2-1,leanDir:Ex(o,s,3)*Math.PI*2,lean:Ex(o,s,4)}}function Ox(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=Ex(o,s,n),p=Ex(o+1,s,n),m=Ex(o,s+1,n),h=Ex(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var kx=[.55,1.7],Ax=.17,jx=.23,Mx=.28;function Nx(e,t,n){let r=Ox(e,t,n^6877377|0,Ax),i=r*r*(3-2*r);return kx[0]+(kx[1]-kx[0])*i}function Px(e,t,n){return Ox(e,t,n^3001105|0,jx)}function Fx(e,t,n){let r=Ox(e,t,n^7840757|0,Mx)*.72+Ox(e,t,n^1688295|0,Mx*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function Ix(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new b(t),s=n/2,c=r/2,l=[],u=Math.floor(i*xx);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=wx(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 _=wx(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 Lx=[`daisy`,`cosmos`,`bellflower`],Rx={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`}},zx=[1,.78,.62],Bx=[0,.07,.11],Vx=[.6,2.7,4.9],Hx=.07,Ux=.011,Wx=.17,Gx=.05,Kx=[.12,.2,.28],qx=new W(`#3e6a26`),Jx=new W(`#548331`);function Yx(e){let t=Rx[e],n=new Xx(!0),r=new Xx(!1),i=new W(t.centerColor);for(let e=0;e<t.blooms;e++){let a=zx[e],o=Vx[e],s=Bx[e]*Math.cos(o),c=Bx[e]*Math.sin(o),l=Hx*Math.cos(o),u=Hx*Math.sin(o),d=new V(s,0,c),f=new V(s+l,a,c+u),p=new V(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,Ux,qx);let m=t.nodDeg*Math.PI/180,h=new V(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new V(-Math.sin(o),0,Math.cos(o)),_=new V().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=Kx[e%Kx.length],r=1.1+e*2.3;n.addLeaf(new V(0,t,0),r,Jx)}return{structure:n.build(),petals:r.build()}}var Xx=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 V(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new V(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 V().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 V(Math.cos(t),0,Math.sin(t)),i=new V(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,Wx*o*.5).add(new V(0,Wx*a*.5,0)),c=e.clone().addScaledVector(r,Wx*o).add(new V(0,Wx*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,Gx/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 K;return e.setAttribute(`position`,new G(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new G(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},Zx=2.6;function Qx(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new b(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=Dx(e,t,Zx);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 $x=1.05,eS=1;function tS(e,t=eS){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*$x+t),e.frustumCulled=!0}function nS(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function rS(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof fb?n:null}return iS(e.getRoot())}function iS(e){if(e instanceof fb)return e;for(let t of e.children){let e=iS(t);if(e)return e}return null}var aS={lush:2.2,sparse:.35,none:0},oS=[`lush`,`sparse`,`none`];function sS(e){if(typeof e==`number`)return e;let t=aS[e];if(t===void 0)throw new y(`BAD_FORMAT`,`Flowers3D density must be one of [${oS.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:oS});return t}var cS=1e4,lS=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],uS=/^#[0-9a-fA-F]{6}$/,dS=class extends Dy{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:oS},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:!1},terrain:{default:``}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)sS(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${oS.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:oS});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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)*sS(t.density));if(n>cS)throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${sS(t.density)} = ${n} plants > ${cS}. 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=>Lx.includes(e)))throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${Lx.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...Lx]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&uS.test(e)))throw new y(`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 y(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new y(`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 y(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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 $i}_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 $i,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)return;let e=rS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=nS(this);else if(this.terrain!==``)throw new y(`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=sS(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),cS);if(t<=0)return;let n=Qx({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering}),r=this.varieties.length>0?this.varieties:Lx,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:lS,o=new b(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}=Yx(r[e]),c=new rc({vertexColors:!0,roughness:1,side:2}),l=new rc({roughness:.85,side:2});fS(c,this.timeUniform,this.swayUniform),fS(l,this.timeUniform,this.swayUniform);let u=new is(n,c,t.length),d=new is(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];hS.set(n.x,this.bedY(n.x,n.z),n.z),gS.setFromAxisAngle(pS,n.rotY),_S.setScalar(this.height*n.scale),mS.compose(hS,gS,_S),u.setMatrixAt(e,mS),d.setMatrixAt(e,mS);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);vS.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,vS),vS.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,vS)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),tS(u),tS(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 fS(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>`,`
5301
+ `;function Xy(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.splatEnvCut={value:t.envCut},e.vertexShader=Vy(e.vertexShader,`#include <common>`,Hy),e.vertexShader=Vy(e.vertexShader,`#include <begin_vertex>`,Uy);let n=e.fragmentShader;n=Vy(n,`#include <common>`,Wy),n=Vy(n,`#include <color_fragment>`,Gy),n=Vy(n,`#include <roughnessmap_fragment>`,Ky),n=Vy(n,`#include <metalnessmap_fragment>`,Jy),n=Vy(n,`#include <normal_fragment_maps>`,Yy),n=Vy(n,`#include <lights_fragment_maps>`,qy),t.hasNormalMaps&&(n=`#define USE_TERRAIN_NORMALMAP\n${n}`),e.fragmentShader=n}var Zy=[`island`,`alpine`,`plains`,`desert`,`grassland`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`,`custom`],Qy=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,$y=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/ground`,eb=1/3,tb=Math.PI/4;function nb(e,t,n){return{texture:`${e}/${t}.png`,normalMap:`${e}/${t}_normal.png`,...n}}function rb(e,t){let n=t.replace(/\/$/,``);switch(e){case`island`:return[nb(n,`sand`,{heightRange:[0,.12],slopeRange:[0,Math.PI/2],heightBlendRange:.05,roughness:.9}),nb(n,`grass`,{heightRange:[.1,.7],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.5,roughness:.85}),nb(n,`snow`,{heightRange:[.8,1],slopeRange:[0,Math.PI/3],heightBlendRange:.1,roughness:.6})];case`alpine`:return[nb(n,`grass`,{heightRange:[0,.45],slopeRange:[0,Math.PI/5],heightBlendRange:.1,roughness:.8}),nb(n,`stone`,{heightRange:[.3,1],slopeRange:[0,Math.PI],heightBlendRange:.25,slopeBlendRange:.5,roughness:.85}),nb(n,`gravel`,{heightRange:[0,1],slopeRange:[Math.PI/5,Math.PI],heightBlendRange:.5,slopeBlendRange:.15,roughness:.9}),nb(n,`snow`,{heightRange:[.55,1],slopeRange:[0,Math.PI/3],heightBlendRange:.12,roughness:.55})];case`plains`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.1,roughness:.8}),nb(n,`dirt`,{heightRange:[.35,.65],slopeRange:[0,Math.PI/5],heightBlendRange:.2,roughness:.9}),nb(n,`gravel`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`desert`:return[nb(n,`sand`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`gravel`,{heightRange:[0,.15],slopeRange:[0,Math.PI/3],heightBlendRange:.08,roughness:.9}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.4,roughness:.85})];case`grassland`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${$y}/grass.jpg`,heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:1,repeat:eb,uvNoiseIntensity:0},{texture:`${$y}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:1,repeat:eb,uvNoiseIntensity:0}]:[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.8}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.9})];case`forest`:return n===`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`?[{texture:`${$y}/dirt_color.jpg`,heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:1,repeat:eb,uvNoiseIntensity:0},{texture:`${$y}/grass.jpg`,heightRange:[-2,-1],roughness:1,repeat:eb,uvNoiseIntensity:0}]:[nb(n,`dirt`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.9}),nb(n,`grass`,{heightRange:[-2,-1],roughness:.8})];case`savanna`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`sand`,{heightRange:[0,.22],slopeRange:[0,Math.PI/4],heightBlendRange:.12,roughness:.95}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`snow`:return[nb(n,`snow`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.18,roughness:.55}),nb(n,`stone`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.35,roughness:.85})];case`wetland`:return[nb(n,`grass`,{heightRange:[0,1],slopeRange:[0,tb],heightBlendRange:.1,slopeBlendRange:.15,roughness:.95}),nb(n,`dirt`,{heightRange:[0,1],slopeRange:[tb,Math.PI],heightBlendRange:.5,slopeBlendRange:.3,roughness:.95})];case`volcanic`:return[nb(n,`stone`,{heightRange:[0,1],slopeRange:[0,Math.PI],heightBlendRange:.1,roughness:.95}),nb(n,`gravel`,{heightRange:[0,.28],slopeRange:[0,Math.PI/3],heightBlendRange:.14,slopeBlendRange:.2,roughness:.95})];case`custom`:return[]}}var ib={scale:100,threshold:.7,blend:.1},ab={scale:55,threshold:.58,blend:.12},ob={scale:85,threshold:.62,blend:.12},sb={scale:48,threshold:.5,blend:.14};function cb(e,t){let n=tt(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 lb(e,t){return e===`grassland`?cb(t,ib):e===`forest`?cb(t,ab):e===`savanna`?cb(t,ob):e===`wetland`?cb(t,sb):null}function ub(e){return e===`savanna`?{from:0,to:2}:e===`grassland`||e===`forest`||e===`wetland`?{from:0,to:1}:null}var db=128,fb=class extends Dy{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:Zy},roughness:{default:.5},detail:{default:4},flatThreshold:{default:.95},islandEdge:{default:null},layers:{default:[]},textureBase:{default:Qy},basins:{default:[]}};size=[200,200];maxHeight=28;seed=1;resolution=128;theme=`island`;roughness=.5;detail=4;flatThreshold=.95;islandEdge=null;layers=[];textureBase=Qy;basins=[];static validateJson(e){let t=e;if(!Zy.includes(t.theme))throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' theme must be one of [${Zy.join(`, `)}], got '${t.theme}'.`,{prop:`theme`,validOptions:Zy});if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new y(`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 y(`BAD_FORMAT`,`Terrain3D '${e.name}' maxHeight must be > 0, got ${t.maxHeight}.`,{prop:`maxHeight`});if(!Number.isInteger(t.resolution)||t.resolution<2||t.resolution>db)throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' resolution must be an integer in [2, ${db}] (grid segments per side), got ${t.resolution}.`,{prop:`resolution`});if(!(t.roughness>0)||!Number.isFinite(t.roughness))throw new y(`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 y(`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 y(`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 y(`BAD_FORMAT`,`Terrain3D '${e.name}' islandEdge must be true, false or null (null = theme default), got ${JSON.stringify(t.islandEdge)}.`,{prop:`islandEdge`});if(!Array.isArray(t.basins))throw new y(`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)||!(t.depth>0))throw new y(`BAD_FORMAT`,`Terrain3D '${e.name}' basins[${n}] needs finite x, z and positive radius, depth, got ${JSON.stringify(t)}.`,{prop:`basins`})}),t.theme===`custom`){if(!Array.isArray(t.layers)||t.layers.length<1||t.layers.length>4)throw new y(`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)=>{hb(e.name,t,n)})}else if(Array.isArray(t.layers)&&t.layers.length>0)throw new y(`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=``;loadedTextures=[];_createObject3D(){let e=new K;return e.setAttribute(`position`,new G(new Float32Array,3)),new Mo(e,new rc({vertexColors:!0}))}heightAt(e,t){let n=0,r=0,i=0;for(let e=this;e;e=e.parent)e instanceof Dy&&(n+=e.position[0]??0,r+=e.position[1]??0,i+=e.position[2]??0);return this._heightmap().heightAt(e-n,t-i)+r}_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]);return(!this.heightmap||t!==this.heightmapKey)&&(this.heightmap=Ry({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}),this.heightmapKey=t),this.heightmap}resolvedLayers(){return this.theme===`custom`?this.layers:rb(this.theme,this.textureBase)}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded()}effectiveIslandEdge(){return this.islandEdge??this.theme===`island`}segments(){return Math.max(2,Math.min(Math.floor(this.resolution),db))}rebuildIfNeeded(){let e=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]);if(e===this.builtKey)return;this.builtKey=e;let t=this._ensureObject3D();t.geometry.dispose(),t.geometry=this.buildGeometry(),t.material.dispose(),this.disposeTextures(),t.material=this.buildMaterial(),t.receiveShadow=!0,t.castShadow=!0}buildGeometry(){let e=this._heightmap(),t=new Gs(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:ub(this.theme),s=o?lb(this.theme,this.seed):null;for(let t=0;t<n.count;t++){let c=n.getX(t),l=n.getZ(t),u=By(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 G(a,3)),t}buildMaterial(){let e=this.resolvedLayers(),t=new rc({vertexColors:!0}),n=typeof document<`u`?new Lc:null,r=(e,t)=>{if(!n||!e)return null;let r=n.load(e);return r.wrapS=Lt,r.wrapT=Lt,r.anisotropy=8,t&&(r.colorSpace=fr),this.loadedTextures.push(r),r},i=e.map(e=>r(e.texture,!0)),a=e.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]=mb());let s={textures:i,normalMaps:a,repeats:e.map(e=>e.repeat??2),roughness:e.map(e=>e.roughness??1),metalness:e.map(e=>e.metalness??0),uvNoiseIntensity:e.map(e=>e.uvNoiseIntensity??.15),envCut:.45,layerCount:Math.min(4,e.length),hasNormalMaps:o};return t.onBeforeCompile=e=>{Xy(e,s)},t.customProgramCacheKey=()=>`incanto-terrain-splat:${+!!o}`,t}disposeTextures(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[]}free(){let e=this._ensureObject3D();e.geometry.dispose(),e.material.dispose(),this.disposeTextures(),this.heightmap=null,super.free()}},pb=null;function mb(){return pb||(pb=new Ko(new Uint8Array([128,128,255,255]),1,1),pb.needsUpdate=!0),pb}function hb(e,t,n){let r=`layers[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new y(`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 y(`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 y(`BAD_FORMAT`,`Terrain3D '${e}' ${r}.${t} must be [min, max] numbers, got ${JSON.stringify(n)}.`,{prop:`layers`})}}var gb=Math.PI/180;async function _b(e,t){let n=await mp(()=>import(`./rapier-DE6a0vmv.js`),[],import.meta.url);return await n.init(),new vb(n,e,t)}var vb=class{R;engine;debugDraw=!1;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.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=cp(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.syncBodies()}step(e){if(this.lastDt=e,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]=Eb(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 jy){if(!e.fixedRotation){let n=t.body.rotation();bb.setFromQuaternion(yb.set(n.x,n.y,n.z,n.w),`XYZ`);let r=e.rotation;r[0]=bb.x/gb,r[1]=bb.y/gb,r[2]=bb.z/gb}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=wb(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`;r.emit(a,i),i.emit(a,r)})}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.snapToGround&&n<=0?this.kcc.enableSnapToGround(.1):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*gb);let r={x:(e.velocity[0]??0)*this.lastDt,y:n*this.lastDt,z:(e.velocity[2]??0)*this.lastDt};this.kcc.computeColliderMovement(t.collider,r,this.R.QueryFilterFlags.EXCLUDE_SENSORS);let i=this.kcc.computedMovement(),a=t.body.translation();t.body.setNextKinematicTranslation({x:a.x+i.x,y:a.y+i.y,z:a.z+i.z}),e._grounded=this.kcc.computedGrounded()}debugLines(){return this.debugDraw?this.world.debugRender().vertices:null}dispose(){this.disconnect(),this.unregisterDebug(),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;bodySet=new Set;syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=t!==this.lastStructure||e.root!==this.lastRoot;n&&(this.lastStructure=t,this.lastRoot=e.root,this.bodySet.clear(),Sb(e.root,this.bodySet)),n&&(this.jointSet.clear(),xb(e.root,this.jointSet));let r=this.bodySet;for(let e of r){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),console.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(n),n)for(let[e,t]of this.entries)r.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;r=e instanceof jy?n.RigidBodyDesc.dynamic():e instanceof My||e instanceof Ay?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed();let[i,a,o]=wb(e);r.setTranslation(i,a,o),yb.setFromEuler(bb.set((e.rotation[0]??0)*gb,(e.rotation[1]??0)*gb,(e.rotation[2]??0)*gb,`XYZ`)),r.setRotation({x:yb.x,y:yb.y,z:yb.z,w:yb.w}),e instanceof jy&&(r.setGravityScale(e.gravityScale),r.setLinvel(e.linearVelocity[0]??0,e.linearVelocity[1]??0,e.linearVelocity[2]??0),e.fixedRotation&&r.lockRotations());let s=this.world.createRigidBody(r),c=Db(n,e);c.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),c.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof Ay&&c.setSensor(!0),e instanceof jy&&c.setMass(e.mass).setFriction(e.friction).setRestitution(e.restitution);let l=this.world.createCollider(c,s);return t={body:s,collider:l,last:[i,a,o],lastV:[0,0,0]},this.entries.set(e,t),this.byColliderHandle.set(l.handle,e),e._colliderChanged=!1,e._physics=this,e instanceof jy&&(e._physics3d=this),t}let r=wb(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 jy){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}},yb=new B,bb=new Fi;function xb(e,t){e instanceof Ny&&t.add(e);for(let n of e.children)xb(n,t)}function Sb(e,t){e instanceof Oy&&t.add(e);for(let n of e.children)Sb(n,t)}var Cb=[0,0,0];function wb(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return Cb[0]=t,Cb[1]=n,Cb[2]=r,Cb}var Tb=[0,0,0];function Eb(e){let t=0,n=0,r=0;for(let i=e.parent;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return Tb[0]=t,Tb[1]=n,Tb[2]=r,Tb}function Db(e,t){let n=t.collider;if(Ey(n,t.name),n.shape===`heightfield`)return Ob(e,t);let r=kb(e,n,t.name),i=n.offset;return Array.isArray(i)&&r.setTranslation(i[0]??0,i[1]??0,i[2]??0),r}function Ob(e,t){let n=t.children.find(e=>e instanceof fb);if(!n)throw new y(`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 kb(e,t,n){let r=t.shape;if(r===`box`){let r=t.size;if(!Array.isArray(r)||r.length!==3||r.some(e=>typeof e!=`number`))throw new y(`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(r===`sphere`){if(typeof t.radius!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': sphere needs "radius".`);return e.ColliderDesc.ball(t.radius)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new y(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2,t.radius)}if(r===`trimesh`){let r=t.vertices,i=t.indices;if(!Array.isArray(r)||!Array.isArray(i))throw new y(`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 y(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'box', 'sphere', 'capsule', 'trimesh', or 'heightfield', got ${JSON.stringify(r)}.`)}var Ab=new Gs(1,1),jb=null;function Mb(){if(jb)return jb;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),jb=new Fs(e),jb}var Nb=new V(0,0,1),Pb=new V,Fb=new V,Ib=new B,Lb=new B,Rb=new V,zb=.5,Bb=class extends Dy{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 Mo(Ab,new bo({transparent:!1,depthWrite:!0,side:2})),this._ensureObject3D().add(this.quadMesh)),this.quadMesh}resolveTexture(){if(!this.texture)return null;if(this.textureRef!==this.texture&&(this.loadedTexture?.dispose(),this.loadedTexture=null,this.textureRef=this.texture,typeof document<`u`)){let e=new Lc().load(this.texture);e.colorSpace=fr;let t=this.pixelArt?Bt:Ut;e.magFilter=t,e.minFilter=t,this.loadedTexture=e}return this.loadedTexture}_syncObject3D(e=1){super._syncObject3D(e);let t=this._quad(),n=t.material,r=this.size[0]??1,i=this.size[1]??1;t.scale.set(this.flipX?-r:r,i,1);let a=this.anchor[0]??.5,o=this.anchor[1]??0;t.position.set((.5-a)*r,(.5-o)*i,0);let s=this.resolveTexture();n.map!==s&&(n.map=s,n.needsUpdate=!0),t.visible=s!==null,n.color.set(this.tint),n.opacity=this.opacity,n.transparent=this.opacity<1,n.alphaTest=this.alphaTest,t.renderOrder=this.renderOrder;let c=this.castShadow&&s!==null;if(t.castShadow=!1,c&&this.shadowMode===`silhouette`){let e=this._shadowCaster();e.visible=!0,e.castShadow=!0,e.scale.set(this.flipX?-r:r,i,1),e.position.set((.5-a)*r,(.5-o)*i,0);let t=e.material;t.map!==s&&(t.map=s,t.needsUpdate=!0);let n=e.customDepthMaterial;n.map!==s&&(n.map=s,n.needsUpdate=!0),t.alphaTest=this.alphaTest,n.alphaTest=this.alphaTest}else this.shadowMesh&&(this.shadowMesh.visible=!1,this.shadowMesh.castShadow=!1);if(c&&this.shadowMode===`blob`){let e=this._blob();e.visible=!0,e.scale.set(r*.52,r*.52,1)}else this.blobMesh&&(this.blobMesh.visible=!1)}_shadowCaster(){return this.shadowMesh||(this.shadowMesh=new Mo(Ab,new bo({colorWrite:!1,depthWrite:!1,side:2})),this.shadowMesh.customDepthMaterial=new ac({depthPacking:dr,side:2}),this._ensureObject3D().add(this.shadowMesh)),this.shadowMesh}_blob(){return this.blobMesh||(this.blobMesh=new Mo(Ab,new bo({map:Mb(),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(Fb),Fb.y=0,Fb.lengthSq()>=1e-6&&this._faceDir(this._quad(),Fb.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(Lb),Rb.copy(e.sunDir).applyQuaternion(Lb.invert()),t.position.addScaledVector(Rb,zb))}_faceToward(e,t){e.getWorldPosition(Pb),Fb.copy(t).sub(Pb),this.billboard===`y`&&(Fb.y=0),!(Fb.lengthSq()<1e-12)&&(Fb.normalize(),Ib.setFromUnitVectors(Nb,Fb),e.parent?.getWorldQuaternion(Lb),e.quaternion.copy(Lb.invert()).multiply(Ib))}_faceDir(e,t){Fb.copy(t),this.billboard===`y`&&(Fb.y=0),!(Fb.lengthSq()<1e-12)&&(Fb.normalize(),Ib.setFromUnitVectors(Nb,Fb),e.parent?.getWorldQuaternion(Lb),e.quaternion.copy(Lb.invert()).multiply(Ib))}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()}},Vb=class extends Bb{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 y(`UNKNOWN_ANIMATION`,`No animation '${e}' on '${this.name}'. Available: [${Object.keys(this.animations).join(`, `)}].`);this.currentAnimation=e,this.frameList=Hb(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(){if(!this.sheet||this.frameWidth<=0||this.frameHeight<=0)return null;if(this.loadedSheetRef!==this.sheet&&(this.sheetTexture?.dispose(),this.sheetTexture=null,this.loadedSheetRef=this.sheet,typeof document<`u`)){let e=new Lc().load(this.sheet);e.colorSpace=fr;let t=this.pixelArt?Bt:Ut;e.magFilter=t,e.minFilter=t,this.sheetTexture=e}let e=this.sheetTexture;if(!e)return null;let t=e.image;if(!t?.width||!t.height)return e;let n=Math.max(1,Math.floor(t.width/this.frameWidth)),r=this.currentFrame%n,i=Math.floor(this.currentFrame/n);return e.repeat.set(this.frameWidth/t.width,this.frameHeight/t.height),e.offset.set(r*this.frameWidth/t.width,1-(i+1)*this.frameHeight/t.height),e}free(){this.sheetTexture?.dispose(),this.sheetTexture=null,super.free()}};function Hb(e,t){if(!Array.isArray(e)||e.length===0)throw new y(`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 Ub=new B,Wb=new B,Gb=new V,Kb=new V(0,0,1),qb=[`screen`,`y`,`none`],Jb=class extends Dy{static typeName=`Billboard3D`;static props={mode:{default:`screen`,options:qb}};mode=`screen`;_lastDesired=null;static validateJson(e){let t=e;if(!qb.includes(t.mode))throw new y(`BAD_FORMAT`,`Billboard3D '${e.name}' mode must be one of [${qb.join(`, `)}], got '${t.mode}'.`,{prop:`mode`,validOptions:qb})}_onRender3D(e){if(this.mode===`none`)return;let t=this._ensureObject3D();if(this.mode===`screen`)e.camera.getWorldQuaternion(Wb);else if(e.camera.getWorldDirection(Gb),Gb.y=0,Gb.lengthSq()>=1e-6)Wb.setFromUnitVectors(Kb,Gb.negate().normalize());else if(this._lastDesired)Wb.copy(this._lastDesired);else return;this._lastDesired||=new B,this._lastDesired.copy(Wb),t.parent?.getWorldQuaternion(Ub),t.parent?t.quaternion.copy(Ub.invert()).multiply(Wb):t.quaternion.copy(Wb)}},Yb=class extends Dy{static typeName=`BoneAttachment3D`;static props={target:{default:``},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(Qb,$b,ex),Zb.compose(Qb,$b,tx),r.updateMatrix(),Xb.copy(r.matrix),r.matrix.copy(i.matrixWorld).invert().multiply(Zb).multiply(Xb))}free(){this.boneObj=null,super.free()}},Xb=new U,Zb=new U,Qb=new V,$b=new B,ex=new V,tx=new V(1,1,1),nx=class extends Dy{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 Xc(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())}},rx=8,ix=.2,ax=.15,ox=1.2,sx=.08,cx=2.5,lx=-20,ux=.002,dx=180/Math.PI,fx=.3,px=.4,mx=.3,hx=.25,gx=new Fi,_x=new B,vx=new U,yx=new V,bx=new V,xx=new V(0,1,0),Sx=class extends Dy{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`},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 jy))throw new y(`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=wx(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]:Cy(e.x,-e.y,t),i=Math.hypot(n[0],n[2])||1;p=n[0]/i,m=n[2]/i}catch{}let g=Tx(r,this.sprintAction),_=wy(h,g),v=1+(this.sprintMultiplier-1)*_,y=h?this.maxSpeed*v:0,b=this.grounded?1:ix,x=(p*y-s[0])/rx*b,S=(m*y-s[2])/rx*b;if(t.applyImpulse([x*c,0,S*c]),!h&&this.grounded&&t.applyImpulse([-s[0]*ax*c,0,-s[2]*ax*c]),f!==null&&f<l*2){let e=ox*(l-f)-s[1]*sx;t.applyImpulse([0,e*c,0])}if(this.grounded&&Tx(r,this.jumpAction)){let e=this.jumpVelocity*(1+(this.sprintJumpMultiplier-1)*_);t.linearVelocity=[s[0],e,s[2]],this.grounded=!1}s[1]<lx?t.gravityScale=0:s[1]<0&&!this.grounded?t.gravityScale=cx:t.gravityScale=1,this.view===`side`&&Math.abs(o[2])>.01&&(t.position=[t.position[0]??0,t.position[1]??0,0]);let C=Ty(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)*dx+this.skinYawOffset,r=t.rotation[1]??0,i=(n-r+540)%360-180,a=this.turnSpeed*e*dx;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*ux,this.pitch=Cx(this.pitch+e.y*ux,-this.pitchMax,-this.pitchMin);let n=t.wheelDelta();n!==0&&this.zoomMax>this.zoomMin&&(this.camDistance=Cx(this.camDistance+n*ux,this.zoomMin,this.zoomMax))}let n=this.findCamera();if(!n)return;let r=this.parent instanceof jy?this.parent:null;if(!r)return;let i=wx(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=by(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=xy(l,u,(t,n,i)=>e.castSphere(t,n,hx,i,r,{staticOnly:!0})?.distance??null,fx,px),u=Sy(u,(t,n)=>e.castRay(t,[0,-1,0],n,r,{staticOnly:!0})?.distance??null,mx))}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`?(yx.set(n.position[0]??0,n.position[1]??0,n.position[2]??0),bx.set(l[0],l[1],l[2]),vx.lookAt(yx,bx,xx),_x.setFromRotationMatrix(vx),gx.setFromQuaternion(_x,`XYZ`)):(gx.set(c.rotation[0],c.rotation[1],c.rotation[2],`YXZ`),_x.setFromEuler(gx),gx.setFromQuaternion(_x,`XYZ`)),n.rotation=[gx.x*dx,gx.y*dx,gx.z*dx]}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 nx&&e.current){this.cameraCache=e;return}for(let n of e.children)t(n)}};return t(e),this.cameraCache}};function Cx(e,t,n){return Math.min(n,Math.max(t,e))}function wx(e){let t=0,n=0,r=0;for(let i=e;i&&i instanceof Dy;i=i.parent)t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0;return[t,n,r]}function Tx(e,t){try{return e.isPressed(t)}catch{return!1}}var Ex=.15,Dx=.7,Ox=.5,kx=.7,Ax=.5;function jx(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 Mx(e,t){let n=jx(e*Ex,t*Ex,4),r=jx(e*Ex*.2,t*Ex*.2,2);return n>Ox-Dx*.5-r*Ax}var Nx=.9;function Px(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 Fx(e,t,n=Nx){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+Px(u,d,0))*n,p=(d+Px(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:Px(o,s,2)*2-1,leanDir:Px(o,s,3)*Math.PI*2,lean:Px(o,s,4)}}function Ix(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=Px(o,s,n),p=Px(o+1,s,n),m=Px(o,s+1,n),h=Px(o+1,s+1,n),g=f+(p-f)*u;return g+(m+(h-m)*u-g)*d}var Lx=[.55,1.7],Rx=.17,zx=.23,Bx=.28;function Vx(e,t,n){let r=Ix(e,t,n^6877377|0,Rx),i=r*r*(3-2*r);return Lx[0]+(Lx[1]-Lx[0])*i}function Hx(e,t,n){return Ix(e,t,n^3001105|0,zx)}function Ux(e,t,n){let r=Ix(e,t,n^7840757|0,Bx)*.72+Ix(e,t,n^1688295|0,Bx*3.1)*.28,i=Math.min(1,Math.max(0,(r-.18)/.64));return i*i*(3-2*i)}function Wx(e){let{seed:t,areaX:n,areaZ:r,count:i,density:a}=e,o=new b(t),s=n/2,c=r/2,l=[],u=Math.floor(i*kx);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=Mx(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 _=Mx(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 Gx=[`daisy`,`cosmos`,`bellflower`],Kx={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`}},qx=[1,.78,.62],Jx=[0,.07,.11],Yx=[.6,2.7,4.9],Xx=.07,Zx=.011,Qx=.17,$x=.05,eS=[.12,.2,.28],tS=new W(`#3e6a26`),nS=new W(`#548331`);function rS(e){let t=Kx[e],n=new iS(!0),r=new iS(!1),i=new W(t.centerColor);for(let e=0;e<t.blooms;e++){let a=qx[e],o=Yx[e],s=Jx[e]*Math.cos(o),c=Jx[e]*Math.sin(o),l=Xx*Math.cos(o),u=Xx*Math.sin(o),d=new V(s,0,c),f=new V(s+l,a,c+u),p=new V(s+l*.25,a*.55,c+u*.25);n.addStem(d,p,f,Zx,tS);let m=t.nodDeg*Math.PI/180,h=new V(Math.sin(m)*Math.cos(o),Math.cos(m),Math.sin(m)*Math.sin(o)),g=new V(-Math.sin(o),0,Math.cos(o)),_=new V().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=eS[e%eS.length],r=1.1+e*2.3;n.addLeaf(new V(0,t,0),r,nS)}return{structure:n.build(),petals:r.build()}}var iS=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 V(Math.cos(a),0,Math.sin(a)),s=[];for(let a=0;a<=5;a++){let c=a/5,l=1-c,u=new V(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 V().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 V(Math.cos(t),0,Math.sin(t)),i=new V(-Math.sin(t),0,Math.cos(t)),a=Math.sin(.6),o=Math.cos(.6),s=e.clone().addScaledVector(r,Qx*o*.5).add(new V(0,Qx*a*.5,0)),c=e.clone().addScaledVector(r,Qx*o).add(new V(0,Qx*a*.8,0)),l=this.vertex(e,n),u=this.vertex(s.clone().addScaledVector(i,$x/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 K;return e.setAttribute(`position`,new G(new Float32Array(this.positions),3)),this.colors&&e.setAttribute(`color`,new G(new Float32Array(this.colors),3)),e.setIndex(this.indices),e.computeVertexNormals(),e}},aS=2.6;function oS(e){let{seed:t,areaX:n,areaZ:r,count:i,clustering:a}=e,o=new b(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=Fx(e,t,aS);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 sS=1.05,cS=1;function lS(e,t=cS){e.computeBoundingSphere();let n=e.boundingSphere;n&&n.radius>=0&&(n.radius=n.radius*sS+t),e.frustumCulled=!0}function uS(e){let t=0,n=0,r=0;for(let i=e;i;i=i.parent)i instanceof Dy&&(t+=i.position[0]??0,n+=i.position[1]??0,r+=i.position[2]??0);return[t,n,r]}function dS(e,t){if(t!==``){let n=e.getNodeOrNull(t);return n instanceof fb?n:null}return fS(e.getRoot())}function fS(e){if(e instanceof fb)return e;for(let t of e.children){let e=fS(t);if(e)return e}return null}var pS={lush:2.2,sparse:.35,none:0},mS=[`lush`,`sparse`,`none`];function hS(e){if(typeof e==`number`)return e;let t=pS[e];if(t===void 0)throw new y(`BAD_FORMAT`,`Flowers3D density must be one of [${mS.join(`, `)}] or a number (plants/m²), got '${e}'.`,{prop:`density`,validOptions:mS});return t}var gS=1e4,_S=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],vS=/^#[0-9a-fA-F]{6}$/,yS=class extends Dy{static typeName=`Flowers3D`;static props={density:{default:`sparse`,options:mS},area:{default:[20,20]},seed:{default:1},varieties:{default:[]},palette:{default:[]},height:{default:.45},clustering:{default:.6},sway:{default:.5},drape:{default:!1},terrain:{default:``}};density=`sparse`;area=[20,20];seed=1;varieties=[];palette=[];height=.45;clustering=.6;sway=.5;drape=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(typeof t.density==`string`)hS(t.density);else if(!(Number.isFinite(t.density)&&t.density>=0))throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' density must be one of [${mS.join(`, `)}] or a number >= 0 (plants/m²), got ${t.density}.`,{prop:`density`,validOptions:mS});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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)*hS(t.density));if(n>gS)throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' blows the plant budget: area ${t.area[0]}×${t.area[1]} m × density ${hS(t.density)} = ${n} plants > ${gS}. 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=>Gx.includes(e)))throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' varieties must be a unique subset of [${Gx.join(`, `)}] ([] = all three), got ${JSON.stringify(t.varieties)}.`,{prop:`varieties`,validOptions:[...Gx]});if(!Array.isArray(t.palette)||!t.palette.every(e=>typeof e==`string`&&vS.test(e)))throw new y(`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 y(`BAD_FORMAT`,`Flowers3D '${e.name}' height must be > 0 meters, got ${t.height}.`,{prop:`height`});if(!(t.clustering>=0)||!(t.clustering<=1))throw new y(`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 y(`BAD_FORMAT`,`Flowers3D '${e.name}' sway must be >= 0, got ${t.sway}.`,{prop:`sway`});if(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Flowers3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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 $i}_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 $i,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)return;let e=dS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=uS(this);else if(this.terrain!==``)throw new y(`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=hS(this.density),t=Math.min(Math.floor((this.area[0]??0)*(this.area[1]??0)*e),gS);if(t<=0)return;let n=oS({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:t,clustering:this.clustering}),r=this.varieties.length>0?this.varieties:Gx,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:_S,o=new b(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}=rS(r[e]),c=new rc({vertexColors:!0,roughness:1,side:2}),l=new rc({roughness:.85,side:2});bS(c,this.timeUniform,this.swayUniform),bS(l,this.timeUniform,this.swayUniform);let u=new is(n,c,t.length),d=new is(s,l,t.length);u.receiveShadow=!0,d.receiveShadow=!0;for(let e=0;e<t.length;e++){let n=t[e];CS.set(n.x,this.bedY(n.x,n.z),n.z),wS.setFromAxisAngle(xS,n.rotY),TS.setScalar(this.height*n.scale),SS.compose(CS,wS,TS),u.setMatrixAt(e,SS),d.setMatrixAt(e,SS);let r=Math.min(Math.floor(n.color01*a.length),a.length-1);ES.set(a[r]).offsetHSL(o.range(-.02,.02),0,o.range(-.05,.05)),d.setColorAt(e,ES),ES.setRGB(1,1,1).offsetHSL(o.range(-.02,.02),0,o.range(-.06,.04)),u.setColorAt(e,ES)}u.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,u.instanceColor&&(u.instanceColor.needsUpdate=!0),d.instanceColor&&(d.instanceColor.needsUpdate=!0),lS(u),lS(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 bS(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>`,`
5302
5302
  vec4 mvPosition = vec4(transformed, 1.0);
5303
5303
  #ifdef USE_INSTANCING
5304
5304
  mvPosition = instanceMatrix * mvPosition;
@@ -5311,7 +5311,7 @@ normal = perturbSplatNormal(normal, vViewPosition, vUvSplat, blendedNormalSample
5311
5311
  mvPosition.z += uFlowerSway * swayW * 0.020 * cos(uFlowerTime * 1.3 + swayPhase * 1.4);
5312
5312
  mvPosition = modelViewMatrix * mvPosition;
5313
5313
  gl_Position = projectionMatrix * mvPosition;
5314
- `)},e.customProgramCacheKey=()=>`incanto-flowers-sway`}var pS=new V(0,1,0),mS=new U,hS=new V,gS=new B,_S=new V,vS=new W;function yS(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 bS=[1,.78,.42];function xS(e){let t=new Float32Array(21),n=new Float32Array(14);for(let r=0;r<3;r++){let i=r/3,a=bS[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 K;return r.setAttribute(`position`,new G(t,3)),r.setAttribute(`uv`,new G(n,2)),r.setIndex([0,1,2,2,1,3,2,3,4,4,3,5,4,5,6]),r}function SS(e){let t=new Float32Array([0,1.025,0,-e,.985,0,0,.985,e,e,.985,0,0,.985,-e]),n=new K;return n.setAttribute(`position`,new G(t,3)),n.setIndex([0,1,2,0,2,3,0,3,4,0,4,1]),n.computeVertexNormals(),n}var CS=`
5314
+ `)},e.customProgramCacheKey=()=>`incanto-flowers-sway`}var xS=new V(0,1,0),SS=new U,CS=new V,wS=new B,TS=new V,ES=new W;function DS(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 OS=[1,.78,.42];function kS(e){let t=new Float32Array(21),n=new Float32Array(14);for(let r=0;r<3;r++){let i=r/3,a=OS[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 K;return r.setAttribute(`position`,new G(t,3)),r.setAttribute(`uv`,new G(n,2)),r.setIndex([0,1,2,2,1,3,2,3,4,4,3,5,4,5,6]),r}function AS(e){let t=new Float32Array([0,1.025,0,-e,.985,0,0,.985,e,e,.985,0,0,.985,-e]),n=new K;return n.setAttribute(`position`,new G(t,3)),n.setIndex([0,1,2,0,2,3,0,3,4,0,4,1]),n.computeVertexNormals(),n}var jS=`
5315
5315
  uniform float time;
5316
5316
  uniform float windStrength;
5317
5317
  uniform float grassHeight;
@@ -5389,7 +5389,7 @@ void main() {
5389
5389
  gl_Position = projectionMatrix * mvPosition;
5390
5390
  #include <fog_vertex>
5391
5391
  }
5392
- `,wS=`
5392
+ `,MS=`
5393
5393
  uniform float time;
5394
5394
  varying vec2 vUv;
5395
5395
  varying float vHeight;
@@ -5547,7 +5547,7 @@ void main() {
5547
5547
  // patches melt into the same fog as the terrain instead of staying vivid.
5548
5548
  #include <fog_fragment>
5549
5549
  }
5550
- `,TS=`
5550
+ `,NS=`
5551
5551
  // incanto atmosphere: standard fog + shadow-receive chunks — both compile
5552
5552
  // out unless the scene declares fog / a light casts (USE_FOG, USE_SHADOWMAP)
5553
5553
  #include <common>
@@ -5651,7 +5651,7 @@ void main() {
5651
5651
  #include <fog_vertex>
5652
5652
  #include <shadowmap_vertex>
5653
5653
  }
5654
- `,ES=`
5654
+ `,PS=`
5655
5655
  // incanto atmosphere: fog + shadow-receive (grass RECEIVES, never casts —
5656
5656
  // per-blade casting would double the vertex bill for invisible gain).
5657
5657
  // receiveShadow is declared by lights_pars_begin in BUILT-IN materials; a
@@ -5723,7 +5723,7 @@ void main() {
5723
5723
  #include <colorspace_fragment>
5724
5724
  #include <fog_fragment>
5725
5725
  }
5726
- `,DS=.4;function OS(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 DS}function kS(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:DS}function AS(e,t){t.length=0,jS(e,t)}function jS(e,t){if(e instanceof My||e instanceof jy){let[n,r,i]=nS(e);t.push({x:n,y:r,z:i,radius:OS(e.collider),footY:r-kS(e.collider)})}for(let n of e.children)jS(n,t)}function MS(e){let t=e.tree;if(!t){let t=[];return AS(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?AS(i,r):r.length=0,t._frameScratch={frameId:t.frameId,bodies:r},r}var NS=6,PS=512;function FS(e,t=`grass`){if(t===`fern`)return IS(e);let n=new b(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 IS(e){let t=new b(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 LS(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<NS;i++){let a=t+(1-t)*i/NS,o=t+(1-t)*(i+1)/NS,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<NS-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 RS(e,t=`grass`){if(typeof document>`u`)return null;let n=PS,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 FS(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 LS(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 Fs(r);return a.colorSpace=fr,a}var zS=.08,BS=.5,VS=12,HS=`
5726
+ `,FS=.4;function IS(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 FS}function LS(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:FS}function RS(e,t){t.length=0,zS(e,t)}function zS(e,t){if(e instanceof My||e instanceof jy){let[n,r,i]=uS(e);t.push({x:n,y:r,z:i,radius:IS(e.collider),footY:r-LS(e.collider)})}for(let n of e.children)zS(n,t)}function BS(e){let t=e.tree;if(!t){let t=[];return RS(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?RS(i,r):r.length=0,t._frameScratch={frameId:t.frameId,bodies:r},r}var VS=6,HS=512;function US(e,t=`grass`){if(t===`fern`)return WS(e);let n=new b(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 WS(e){let t=new b(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 GS(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<VS;i++){let a=t+(1-t)*i/VS,o=t+(1-t)*(i+1)/VS,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<VS-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 KS(e,t=`grass`){if(typeof document>`u`)return null;let n=HS,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 US(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 GS(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 Fs(r);return a.colorSpace=fr,a}var qS=.08,JS=.5,YS=12,XS=`
5727
5727
  // GLSL Simplex Noise 3D — https://github.com/ashima/webgl-noise (MIT)
5728
5728
  vec3 ezMod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
5729
5729
  vec4 ezMod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
@@ -5775,9 +5775,9 @@ float ezSimplex3(vec3 v) {
5775
5775
  m = m * m;
5776
5776
  return 42.0 * dot(m * m, vec4(dot(g0, x0), dot(g1, x1), dot(g2, x2), dot(g3, x3)));
5777
5777
  }
5778
- `;function US(e){return`#include <lights_fragment_maps>
5778
+ `;function ZS(e){return`#include <lights_fragment_maps>
5779
5779
  iblIrradiance *= ${e.toFixed(3)};
5780
- radiance *= ${e.toFixed(3)};`}function WS(e,t){e.userData.envCut=t,e.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace(`#include <lights_fragment_maps>`,US(t))},e.customProgramCacheKey=()=>`incanto-env-cut-${t.toFixed(3)}`}function GS(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;
5780
+ radiance *= ${e.toFixed(3)};`}function QS(e,t){e.userData.envCut=t,e.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace(`#include <lights_fragment_maps>`,ZS(t))},e.customProgramCacheKey=()=>`incanto-env-cut-${t.toFixed(3)}`}function $S(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;
5781
5781
  uniform float uLeafFadeEnd;
5782
5782
  attribute vec3 anchor;
5783
5783
  `:``,a=r?`
@@ -5787,16 +5787,16 @@ attribute vec3 anchor;
5787
5787
  #endif
5788
5788
  vec4 ezAnchorWorld = modelMatrix * ezAnchor;
5789
5789
  float ezFade = step(uLeafFadeStart + 1e-4, uLeafFadeEnd) * smoothstep(uLeafFadeStart, max(uLeafFadeEnd, uLeafFadeStart + 1e-4), distance(cameraPosition, ezAnchorWorld.xyz));
5790
- 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() {`,`${HS}\nvoid main() {`).replace(`#include <project_vertex>`,`
5790
+ 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() {`,`${XS}\nvoid main() {`).replace(`#include <project_vertex>`,`
5791
5791
  vec4 mvPosition = vec4(transformed, 1.0);
5792
5792
  #ifdef USE_INSTANCING
5793
5793
  mvPosition = instanceMatrix * mvPosition;
5794
5794
  #endif
5795
- float windOffset = 2.0 * 3.14 * ezSimplex3(mvPosition.xyz / ${VS.toFixed(1)});
5796
- mvPosition.xyz += uv.y * ${zS.toFixed(3)} * vec3(1.0, 0.0, 1.0) * (
5797
- 0.5 * sin(uTreeTime * ${BS.toFixed(2)} + windOffset) +
5798
- 0.3 * sin(2.0 * uTreeTime * ${BS.toFixed(2)} + 1.3 * windOffset) +
5799
- 0.2 * sin(5.0 * uTreeTime * ${BS.toFixed(2)} + 1.5 * windOffset)
5795
+ float windOffset = 2.0 * 3.14 * ezSimplex3(mvPosition.xyz / ${YS.toFixed(1)});
5796
+ mvPosition.xyz += uv.y * ${qS.toFixed(3)} * vec3(1.0, 0.0, 1.0) * (
5797
+ 0.5 * sin(uTreeTime * ${JS.toFixed(2)} + windOffset) +
5798
+ 0.3 * sin(2.0 * uTreeTime * ${JS.toFixed(2)} + 1.3 * windOffset) +
5799
+ 0.2 * sin(5.0 * uTreeTime * ${JS.toFixed(2)} + 1.5 * windOffset)
5800
5800
  );${a}
5801
5801
  mvPosition = modelViewMatrix * mvPosition;
5802
5802
  gl_Position = projectionMatrix * mvPosition;
@@ -5810,18 +5810,18 @@ attribute vec3 anchor;
5810
5810
  if (diffuseColor.a < ezCutoff) discard;
5811
5811
  #endif
5812
5812
  #endif
5813
- `).replace(`#include <lights_fragment_maps>`,US(n))},e.customProgramCacheKey=r?()=>`incanto-eztree-leaf-wind-v5-fade-${n.toFixed(3)}`:()=>`incanto-eztree-leaf-wind-v4-${n.toFixed(3)}`}var KS=40,qS=1;function JS(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() {`,`${HS}\nvoid main() {`).replace(`#include <project_vertex>`,`
5813
+ `).replace(`#include <lights_fragment_maps>`,ZS(n))},e.customProgramCacheKey=r?()=>`incanto-eztree-leaf-wind-v5-fade-${n.toFixed(3)}`:()=>`incanto-eztree-leaf-wind-v4-${n.toFixed(3)}`}var eC=40,tC=1;function nC(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() {`,`${XS}\nvoid main() {`).replace(`#include <project_vertex>`,`
5814
5814
  vec4 mvPosition = vec4(transformed, 1.0);
5815
5815
  #ifdef USE_INSTANCING
5816
5816
  mvPosition = instanceMatrix * mvPosition;
5817
5817
  #endif
5818
- float tuftPhase = 6.2832 * ezSimplex3(vec3(mvPosition.xz / ${KS.toFixed(1)}, 0.0));
5818
+ float tuftPhase = 6.2832 * ezSimplex3(vec3(mvPosition.xz / ${eC.toFixed(1)}, 0.0));
5819
5819
  mvPosition.xz += uv.y * uTuftWind *
5820
- sin(uTuftTime * ${qS.toFixed(1)} + tuftPhase) *
5821
- cos(uTuftTime * ${(1.4*qS).toFixed(1)} + tuftPhase) * vec2(1.0, 0.8);
5820
+ sin(uTuftTime * ${tC.toFixed(1)} + tuftPhase) *
5821
+ cos(uTuftTime * ${(1.4*tC).toFixed(1)} + tuftPhase) * vec2(1.0, 0.8);
5822
5822
  mvPosition = modelViewMatrix * mvPosition;
5823
5823
  gl_Position = projectionMatrix * mvPosition;
5824
- `)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var YS=[`grass`,`flowers`,`reeds`],XS=[`blades`,`simple`,`mesh`,`tufts`],ZS=[`grass`,`fern`],QS={grass:.08,flowers:.14,reeds:.05},$S=[.75,1.25],eC=.05,tC=.25,nC=2e5,rC=8,iC=.05,aC=.38,oC=[.75,1.3],sC=.1,cC=.42,lC=[.6,1.6],uC=.8,dC=.9,fC=.04,pC=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],mC=1/3,hC=1.5,gC=1.45,_C=.4,vC=.13,yC=[.85,1.2],bC=[.8,1.3],xC=`#b3a24e`,SC=.8,CC=.5,wC=class e extends Dy{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:YS},style:{default:`mesh`,options:XS},tuftStyle:{default:`grass`,options:ZS},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:!1},terrain:{default:``},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=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!YS.includes(t.kind))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${YS.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:YS});if(!XS.includes(t.style))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${XS.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:XS});if(!ZS.includes(t.tuftStyle))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${ZS.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:ZS});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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 y(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>nC)throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${nC} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new y(`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 y(`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 y(`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 y(`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(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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 $i}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()}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;t.time&&(t.time.value=this.time),t.windStrength&&(t.windStrength.value=this.sway*(this.isMesh?aC:tC)),(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));let n=this.benderSlots;for(let e=0;e<4;e++){let t=this.pickedBenders[e];t?n[e]?.set(t.x,t.y,t.z,t.radius):n[e]?.set(0,0,0,0)}}else if(this.isTufts)e.matrix.identity(),this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*vC);else if(this.sway>0){let t=Math.sin(this.time*1.7)*eC*this.sway,n=Math.sin(this.time*1.3+1.7)*eC*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]=nS(this);this.drape&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of MS(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=CC&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+SC})}return yS(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new $i,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?rC:this.isTufts?mC: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)tS(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,!this.drape)return;let e=rS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=nS(this);else if(this.terrain!==``)throw new y(`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}buildMeshField(e){let t=Ix({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*rC}),n=this.coverage>=1?t:t.filter(e=>Fx(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 xi(0,0,0,0));let s=Qs.merge([J.lights,J.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*aC},topColor:{value:new W(this.colorB)},bottomColor:{value:new W(this.colorA)},groundColor:{value:new W(this.groundColor)},sunDirection:{value:new V(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 tc({vertexShader:TS,fragmentShader:ES,uniforms:s,fog:!0,lights:!0,side:2});let c=xS(iC),l=a.length,u=Math.max(l,1),d=new is(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new b(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=Dx(t.x,t.z),r=Nx(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range(oC[0],oC[1]),s=this.height*r*(.55+t.scale*.6);AC.set(t.x,this.bedY(t.x,t.z),t.z),jC.setFromAxisAngle(OC,t.rotY),MC.set(o,s,o),d.setMatrixAt(e,kC.compose(AC,jC,MC));let c=n.leanDir+f.range(-.6,.6),l=(sC+cC*(.5*n.lean+.5*f.next()))*(1+uC*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(lC[0],lC[1])*(1+dC*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=Px(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new Xo(p,4)),c.setAttribute(`aClumpHue`,new Xo(m,1)),c.setAttribute(`aDry`,new Xo(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new is(SS(fC),new rc({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new b(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=Nx(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);AC.set(i.x,this.bedY(i.x,i.z),i.z),jC.setFromAxisAngle(OC,i.rotY),MC.set(1,o,1),t.setMatrixAt(r,kC.compose(AC,jC,MC));let s=n.next(),c=pC[s<.45?0:s<.75?1:2];t.setColorAt(r,FC.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=Ix({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*mC}),n=this.coverage>=1?t:t.filter(e=>Fx(e.x,e.z,this.seed)<=this.coverage);this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*vC};let r=new rc({alphaTest:.5,side:2,roughness:1}),i=RS(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),JS(r,this.tuftTime,this.tuftStrength);let a=new is(EC(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new b(this.seed+7403357),s=NC.set(this.colorA),c=PC.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(Nx(t.x,t.z,this.seed)-1)*_C,i=this.height*hC*r*o.range(yC[0],yC[1]),l=i*gC*o.range(bC[0],bC[1]);AC.set(t.x,this.bedY(t.x,t.z),t.z),jC.setFromAxisAngle(OC,t.rotY),MC.set(l,i,l),a.setMatrixAt(e,kC.compose(AC,jC,MC));let u=Dx(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,Px(t.x,t.z,this.seed)*.8-.1));FC.copy(s).lerp(c,d).lerp(IC.set(xC),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,FC)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=Ix({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 xi(0,0,0,0));let n=Qs.merge([J.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*tC},topColor:{value:new W(this.colorB)},bottomColor:{value:new W(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new tc({vertexShader:CS,fragmentShader:wS,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=TC(this.height),i=new is(r,this.bladesMaterial,Math.max(e,1)),a=new is(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];AC.set(e.x,this.bedY(e.x,e.z),e.z),MC.setScalar(e.scale),jC.setFromAxisAngle(OC,e.rotY),i.setMatrixAt(n,kC.compose(AC,jC,MC)),jC.setFromAxisAngle(OC,e.rotY+Math.PI/2),a.setMatrixAt(n,kC.compose(AC,jC,MC))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new rc({side:2,roughness:1}),n=new is(DC(QS[this.kind]??.08),t,Math.max(e,1));n.count=e,n.receiveShadow=!0;let r=new b(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=NC.set(this.colorA),s=PC.set(this.colorB);for(let t=0;t<e;t++){let e=r.range(-i,i),c=r.range(-a,a);AC.set(e,this.bedY(e,c),c),jC.setFromAxisAngle(OC,r.range(0,Math.PI*2)),MC.set(1,this.height*r.range($S[0],$S[1]),1),kC.compose(AC,jC,MC),n.setMatrixAt(t,kC),n.setColorAt(t,FC.copy(o).lerp(s,r.next()))}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 TC(e){let t=new Gs(1,e,1,1);return t.translate(0,e/2,0),t}function EC(){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 K;return i.setAttribute(`position`,new G(new Float32Array(e),3)),i.setAttribute(`normal`,new G(new Float32Array(t),3)),i.setAttribute(`uv`,new G(new Float32Array(n),2)),i.setIndex(r),i}function DC(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 K;return i.setAttribute(`position`,new G(n,3)),i.setAttribute(`normal`,new G(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var OC=new V(0,1,0),kC=new U,AC=new V,jC=new B,MC=new V,NC=new W,PC=new W,FC=new W,IC=new W,LC=class extends Dy{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 rl}_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}}},RC=class extends Dy{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new el}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},zC=[`color`,`metalness`,`roughness`,`emissive`,`emissiveIntensity`,`wireframe`,`flatShading`,`opacity`,`clearcoat`,`clearcoatRoughness`,`envMapIntensity`,`depthTest`,`depthWrite`,`map`,`normalMap`,`repeat`],BC=class extends Dy{static typeName=`MeshInstance3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;static validateJson(e){HC(e.material,e.name)}geometryKey=``;textureKey=``;loadedTextures=[];_createObject3D(){return new Mo(new zs(1,1,1),new ic)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=`${this.mesh}:${JSON.stringify(this.size)}`;t!==this.geometryKey&&(e.geometry.dispose(),e.geometry=UC(this.mesh,this.size),this.geometryKey=t);let n=e.material;VC(n,this.material),this.syncTextures(n),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}syncTextures(e){let t=JSON.stringify([this.material.map??``,this.material.normalMap??``,this.material.repeat??null]);if(t===this.textureKey)return;this.textureKey=t;for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let n=e.map!==null||e.normalMap!==null;e.map=null,e.normalMap=null;let r=typeof document<`u`?new Lc:null;r&&this.material.map&&(e.map=this.loadTexture(r,this.material.map,!0)),r&&this.material.normalMap&&(e.normalMap=this.loadTexture(r,this.material.normalMap,!1)),(n||e.map||e.normalMap)&&(e.needsUpdate=!0)}loadTexture(e,t,n){let r=e.load(t);r.wrapS=Lt,r.wrapT=Lt;let[i,a]=this.material.repeat??[1,1];return r.repeat.set(i,a),r.anisotropy=4,n&&(r.colorSpace=fr),this.loadedTextures.push(r),r}free(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],super.free()}};function VC(e,t){e.color.set(t.color??`#ffffff`),e.metalness=t.metalness??0,e.roughness=t.roughness??1,e.wireframe=t.wireframe??!1,e.emissive.set(t.emissive??`#000000`),e.emissiveIntensity=t.emissiveIntensity??1;let n=t.opacity??1;e.opacity=n,e.transparent=n<1;let r=t.clearcoat??0;e.clearcoat>0!=r>0&&(e.needsUpdate=!0),e.clearcoat=r,e.clearcoatRoughness=t.clearcoatRoughness??0,e.envMapIntensity=t.envMapIntensity??1,e.depthTest=t.depthTest??!0,e.depthWrite=t.depthWrite??!0;let i=t.flatShading??!1;e.flatShading!==i&&(e.flatShading=i,e.needsUpdate=!0)}function HC(e,t,n=`MeshInstance3D`){let r=e=>{throw new y(`BAD_FORMAT`,`${n} '${t}' ${e}`,{prop:`material`,validOptions:[...zC]})};(typeof e!=`object`||!e||Array.isArray(e))&&r(`material must be an object, got ${JSON.stringify(e)}.`);for(let t of Object.keys(e))zC.includes(t)||r(`material has unknown key '${t}' — must be one of [${zC.join(`, `)}].`);for(let t of[`map`,`normalMap`]){let n=e[t];n!==void 0&&(typeof n!=`string`||n.length===0)&&r(`material.${t} must be a non-empty texture URL string, got ${JSON.stringify(n)}.`)}if(e.repeat!==void 0){let t=e.repeat;(!Array.isArray(t)||t.length!==2||!t.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0))&&r(`material.repeat must be [u, v] with positive numbers, got ${JSON.stringify(t)}.`),!e.map&&!e.normalMap&&r(`material.repeat tiles nothing — add a 'map' and/or 'normalMap' texture URL.`)}for(let t of[`metalness`,`roughness`,`opacity`,`clearcoat`,`clearcoatRoughness`]){let n=e[t];n!==void 0&&!(typeof n==`number`&&n>=0&&n<=1)&&r(`material.${t} must be a number in 0..1, got ${JSON.stringify(n)}.`)}e.envMapIntensity!==void 0&&!(typeof e.envMapIntensity==`number`&&Number.isFinite(e.envMapIntensity)&&e.envMapIntensity>=0)&&r(`material.envMapIntensity must be a number >= 0, got ${JSON.stringify(e.envMapIntensity)}.`);for(let t of[`wireframe`,`flatShading`,`depthTest`,`depthWrite`]){let n=e[t];n!==void 0&&typeof n!=`boolean`&&r(`material.${t} must be a boolean, got ${JSON.stringify(n)}.`)}}function UC(e,t){let n=t[0]??1,r=t[1]??1,i=t[2]??1;switch(e){case`box`:return new zs(n,r,i);case`sphere`:return new Ks(n,32,16);case`gem`:return new Ws(n,0);case`capsule`:return new Bs(n,r,8,16);case`plane`:{let e=new Gs(n,i);return e.rotateX(-Math.PI/2),e}case`cylinder`:return new Vs(n,n,r,24);default:throw new y(`PROP_TYPE_MISMATCH`,`MeshInstance3D.mesh must be one of box|sphere|capsule|plane|cylinder|gem, got '${e}'.`)}}var WC=class extends Dy{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;GC(t.sections,e.name),HC(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new y(`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 Mo(new K,new ic)}_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=JC(this.sections,this.slices,this.smooth),this.geometryKey=t),VC(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}};function GC(e,t){let n=e=>{throw new y(`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 KC(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 qC(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:KC(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,KC(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,KC(a.height,o.height,s.height,c.height,n)),y:KC(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,KC(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function JC(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=qC(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 K;return d.setAttribute(`position`,new G(o,3)),d.setIndex(l),d.computeVertexNormals(),d}var YC={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`},XC={};for(let[e,t]of Object.entries(YC))XC[`mixamorig${e}`]=t,XC[`mixamorig:${e}`]=t;function ZC(e,t,n){let r=[],i=new Set,a=new B,o=new B,s=new B,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 V).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new V).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=XC[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 xc&&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 xc(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Cc&&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 Cc(`${m}.position`,[...l.times],[...e]))}}return{clip:new wc(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}var QC=.2,$C=class extends Dy{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Dy.props,model:{default:``},animation:{default:``},targetHeight:{default:0},castShadow:{default:!1},animationLoop:{default:!0},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1},roughness:{default:-1}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitGroup=null;mixer=null;playing=``;currentAction=null;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new $i}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,console.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=_v(n.scene);let r=new $i;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new Dl(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;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=ew(this.fitGroup).getSize(new V),n=t.y>0?this.targetHeight/t.y:e;n<.05||n>20?(this.fitGroup.scale.setScalar(1),console.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)}}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 W(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)}}syncAnimation(e){if(!this.mixer||!this.entry||this.playing===this.animation)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(QC),this.currentAction=null,this.playing=``;return}let t=this.entry.animations.find(e=>e.name===this.animation)??null;if(!t&&(this.animation.startsWith(`$`)||/\.(glb|gltf)$/i.test(this.animation))){let n=e.getAnimation(this.animation);if(n.status===`loading`)return;if(n.status===`ready`&&n.scene){let e=(n.clip?n.clips.find(e=>e.name===n.clip):void 0)??n.clips[0];if(e)if(this.entry.isVrm&&this.entry.vrm){let r=this.entry.retargeted.get(this.animation);if(r)t=r;else{let r=ZC(e,n.scene,this.entry.vrm);r.skippedBones.length>0&&console.warn(`incanto: retarget '${this.animation}' skipped bones: ${r.skippedBones.join(`, `)}`),this.entry.retargeted.set(this.animation,r.clip),t=r.clip}}else t=e}}if(this.playing=this.animation,t){let e=this.mixer.clipAction(t);if(e.reset(),this.animationLoop?e.setLoop($n,1/0):(e.setLoop(Qn,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){let n=t.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,QC,n)}this.currentAction=e}else console.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)`}`)}update(e){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.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function ew(e){e.updateWorldMatrix(!0,!0);let t=new Ca,n=new Ca,r=e.matrixWorld.clone().invert(),i=new U,a=new V;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 tw=.01,nw=class e extends Dy{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`,...at]},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`&&!at.includes(t.preset))throw new y(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${at.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:at});if(t.blend!==`add`&&t.blend!==`normal`)throw new y(`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){ot(this,this.preset,_e(e.typeName));let t=this.tree?.engine?.rng??new b(4660);this.sim=new ct({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*tw,(this.speed[1]??0)*tw],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*tw,(this.gravity[1]??0)*tw,(this.gravity[2]??0)*tw],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 W,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 K;e.setAttribute(`position`,new G(this.positions,3)),e.setAttribute(`color`,new G(this.colors,4));let t=new Ds({size:(this.sizeStart+this.sizeEnd)/2*tw,map:sw(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new Ms(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:rw.set(this.colorStart),o=iw.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))),aw.copy(t).lerp(o,e.t),r[c*4]=aw.r,r[c*4+1]=aw.g,r[c*4+2]=aw.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}},rw=new W,iw=new W,aw=new W,ow=null;function sw(){if(ow)return ow;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 Ko(t,64,64,cn);return n.magFilter=Ut,n.minFilter=Ut,n.generateMipmaps=!1,n.needsUpdate=!0,ow=n,n}var cw=128,lw=class extends Dy{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 $i,t=new K;t.setAttribute(`position`,new G(new Float32Array(cw*2*3),3));let n=new bo({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new Mo(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(uw);let e=this.points[this.points.length-1];(!e||(e.x-uw.x)**2+(e.y-uw.y)**2+(e.z-uw.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:uw.x,y:uw.y,z:uw.z,t:this.clock}),this.points.length>cw&&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 W(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;dw.set(r.x-n.x,r.y-n.y,r.z-n.z),dw.lengthSq()<1e-8&&dw.set(0,1,0),fw.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),pw.crossVectors(dw,fw).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+pw.x*s,n.y+pw.y*s,n.z+pw.z*s),o.setXYZ(t*2+1,n.x-pw.x*s,n.y-pw.y*s,n.z-pw.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(cw-1)*6){let e=[];for(let t=0;t<cw-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}},uw=new V,dw=new V,fw=new V,pw=new V;function mw(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 hw={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}}},gw=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function _w(e){let t=hw[e];if(!t)throw new y(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${gw.join(`, `)}].`,{prop:`preset`,validOptions:gw});return structuredClone(t)}var vw={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 yw(e){if(!gw.includes(e))throw new y(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${gw.join(`, `)}].`,{prop:`preset`,validOptions:gw});return structuredClone(vw[e.replace(/-forest$/,``)])}var bw=.45,xw=.45,Sw=.55,Cw=.15,ww=.07,Tw=.035;function Ew(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 Dw(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,xw);x=(r-f)/e*t,S=xw*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(Cw,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-Sw)+e/i*Sw,S=S*(1-Sw)+t/i*Sw,C=C*(1-Sw)+n/i*Sw;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=bw+(1-bw)*w,D=t[o],O=E*(1-ww*Ew(D,1)),ee=(Ew(D,2)-.5)*2*Tw;a[o*3]=O*(1+ee),a[o*3+1]=O,a[o*3+2]=O*(1-ee)}return{normals:i,colors:a}}var Ow=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 kw(e,t,n){let r=new Ow(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new V,orientation:new Fi,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;)Aw(e,r,i,a,a.shift());Lw(i,n);let o=new K;o.setAttribute(`position`,new G(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new G(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new G(new Float32Array(i.branchUvs),2)),o.setIndex(new G(Rw(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new K,s.setAttribute(`position`,new G(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new G(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new G(new Float32Array(i.leafUvs),2)),s.setIndex(new G(Rw(i.leafIndices,i.leafVerts),1));let t=Dw(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new G(t.normals,3)),s.setAttribute(`color`,new G(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function Aw(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 V,d=new V,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new V(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new V(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 V(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 B().setFromEuler(o),h=new B().setFromAxisAngle(new V(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new B().setFromUnitVectors(new V(0,1,0),new V(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}Iw(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&&Fw(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?Pw(e,t,n,l,u):i.level<e.branch.levels&&Nw(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function jw(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 V().lerpVectors(r.origin,i.origin,a),s=new B().setFromEuler(r.orientation),c=new B().setFromEuler(i.orientation);return{origin:o,orientation:new Fi().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function Mw(e,t,n){let r=new B().setFromAxisAngle(new V(1,0,0),t/(180/Math.PI)),i=new B().setFromAxisAngle(new V(0,1,0),n),a=new B().setFromEuler(e);return new Fi().setFromQuaternion(a.multiply(i.multiply(r)))}function Nw(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=jw(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=Mw(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 Pw(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=jw(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=Mw(s.orientation,e.leaves.angle,c);Fw(e,t,n,s.origin,l,i)}}function Fw(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 V(-t,s,0),new V(-t,0,0),new V(t,0,0),new V(t,s,0)];for(let t of c)t.applyEuler(new Fi(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 Iw(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 Lw(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 Rw(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var zw=[`simple`,`medium`,`high`],Bw=[`conifer`,`broadleaf`,`dead`,`bush`];function Vw(e,t,n){return new y(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var Hw={simple:0,medium:1,high:2},Uw=[5,7,10],Ww=[2,3,4],Gw=[6,8,12],Kw=[2,3,3],qw=[0,1,2],Jw=[3,4,5],Yw=3;function Xw(e,t){if(!zw.includes(e))throw Vw(`tier`,e,zw);if(!Bw.includes(t))throw Vw(`type`,t,Bw);let n=e,r=t,i=Hw[n];return{tier:n,type:r,trunkRadialSegments:Uw[i],canopyLayers:r===`conifer`?Ww[i]:0,canopySegments:Gw[i],blobCount:r===`broadleaf`||r===`bush`?Kw[i]:0,blobDetail:qw[i],branchCount:r===`dead`?Jw[i]:r===`conifer`&&n===`high`?Yw:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var Zw=.02,Qw={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 $w(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=Qw[e.type],o=[],s=new Vs(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 Vs(.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 U().makeRotationY(c).multiply(new U().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=tT(o);return rT(c,new W(n),.7,1.05,t),c}function eT(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 Hs(o,s,e.canopySegments).toNonIndexed();nT(c,t,Zw),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new Hs(.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 U().makeRotationY(a).multiply(new U().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=Qw[e.type];for(let i=0;i<e.blobCount;i++){let a=new Ws((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),nT(a,t,Zw);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=tT(r);return rT(i,new W(n),.62,1.18,t),i}function tT(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 K;return a.setAttribute(`position`,new G(n,3)),a.setAttribute(`normal`,new G(r,3)),a}function nT(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 rT(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 W;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 G(o,3))}var iT=500,aT=15e5,oT=[.8,1.2],sT=.28,cT=.12,lT=.055,uT=.11,dT=3,fT=101,pT=[.78,.7,.45],mT=.45,hT=.55,gT=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,_T=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,vT={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`]}},yT=class e extends Dy{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:zw},type:{default:`conifer`,options:Bw},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:!1},terrain:{default:``}};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=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(Xw(t.tier,t.type),!(t.height>0))throw new y(`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>iT)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${iT}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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 y(`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 y(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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=ST(t.tier,t.type),r=n*t.count;if(r>aT)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${aT}. Lower count (max ${Math.floor(aT/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 $i}_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 $i,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)return;let e=rS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=nS(this);else if(this.terrain!==``)throw new y(`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=Xw(this.tier,this.type),t=new b(this.seed),n=$w(e,t,this.trunkColor),r=eT(e,t,this.canopyColor),i=new is(n,OT(),this.count);AT(i);let a=null;r&&(a=new is(r,OT(),this.count),AT(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),kT(i),a&&kT(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=vT[this.tier][this.type],t=Math.min(dT,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=TT(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new sl,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=_w(o);this.type===`dead`&&(s.leaves.count=0);let c=kw(s,this.seed+a*fT,1),l=this.buildBarkMaterial(o,i),u=new is(c.branches,l,t);AT(u);let d=null;if(c.leaves){let e=new rc({color:r.clone().multiply(new W(pT[0],pT[1],pT[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||CT(s.leaves.style);i&&(e.map=xT(i,n,e=>{e.colorSpace=fr,e.flipY=!1},e=>wT(e))),GS(e,this.swayUniform,mT,this.leafFadeUniform??void 0),d=new is(c.leaves,e,t),AT(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 b(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)kT(e.branches),e.leaves&&kT(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new rc({color:new W(this.trunkColor),roughness:1});let r=yw(t),i=new rc({color:this.trunkColor===e.props.trunkColor?.default?new W(r.tint):DT(this.trunkColor),roughness:1});return WS(i,hT),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 xT(e,`${_T}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=Lt,e.wrapT=Lt,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=fr)})}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);NT.set(a,this.drape?this.bedY(a,o):0,o),PT.setFromAxisAngle(jT,e.range(0,Math.PI*2));let s=this.height*e.range(oT[0],oT[1]),c=s*e.range(.9,1.1);FT.set(c,s,c),MT.compose(NT,PT,FT),IT.setHSL(sT,cT,.92).offsetHSL(e.range(-.055,lT),0,e.range(-.11,uT)),t(i,MT,IT)}}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()}},bT=new Map;function xT(e,t,n,r){let i=bT.get(t);if(i)return i;let a=new bi;return n(a),e.load(t,e=>{a.image=e,r?r(a):a.needsUpdate=!0}),bT.set(t,a),a}function ST(e,t){let n=0;for(let r of new Set(vT[e][t]??[])){let e=_w(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,mw(e).total)}return n}function CT(e){return`${gT}/${e}_color.png`}function wT(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 TT(e){let t=new W(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(ET,.18)}var ET=new W(1,1,1);function DT(e){let t=new W(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function OT(){return new rc({vertexColors:!0,roughness:1,flatShading:!0})}function kT(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),tS(e)}function AT(e){e.castShadow=!0,e.receiveShadow=!0}var jT=new V(0,1,0),MT=new U,NT=new V,PT=new B,FT=new V,IT=new W,LT=[[[.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]]],RT=2e5,zT=class extends Dy{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 zs(1,1,1),t=new tc({vertexShader:VT,fragmentShader:HT});this.mesh=new is(e,t,RT),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of BT)this.mesh.geometry.setAttribute(e,new Xo(new Float32Array(RT*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 U,t=0;for(let[n,r]of this.map){if(t>=RT)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=LT[r]??LT[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(BT[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}},BT=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],VT=`
5824
+ `)},e.customProgramCacheKey=()=>`incanto-tuft-wind`}var rC=[`grass`,`flowers`,`reeds`],iC=[`blades`,`simple`,`mesh`,`tufts`],aC=[`grass`,`fern`],oC={grass:.08,flowers:.14,reeds:.05},sC=[.75,1.25],cC=.05,lC=.25,uC=2e5,dC=8,fC=.05,pC=.38,mC=[.75,1.3],hC=.1,gC=.42,_C=[.6,1.6],vC=.8,yC=.9,bC=.04,xC=[`#f5f1e2`,`#e9d052`,`#8d7bd9`],SC=1/3,CC=1.5,wC=1.45,TC=.4,EC=.13,DC=[.85,1.2],OC=[.8,1.3],kC=`#b3a24e`,AC=.8,jC=.5,MC=class e extends Dy{static typeName=`Foliage3D`;static props={kind:{default:`grass`,options:rC},style:{default:`mesh`,options:iC},tuftStyle:{default:`grass`,options:aC},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:!1},terrain:{default:``},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=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(!rC.includes(t.kind))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' kind must be one of [${rC.join(`, `)}], got '${t.kind}'.`,{prop:`kind`,validOptions:rC});if(!iC.includes(t.style))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' style must be one of [${iC.join(`, `)}], got '${t.style}'.`,{prop:`style`,validOptions:iC});if(!aC.includes(t.tuftStyle))throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' tuftStyle must be one of [${aC.join(`, `)}], got '${t.tuftStyle}'.`,{prop:`tuftStyle`,validOptions:aC});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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 y(`BAD_FORMAT`,`Foliage3D '${e.name}' needs density > 0 and maxInstances >= 1, got density ${t.density}, maxInstances ${t.maxInstances}.`,{prop:`density`});if(t.maxInstances>uC)throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' maxInstances is capped at ${uC} (got ${t.maxInstances}) — split giant fields into multiple nodes.`,{prop:`maxInstances`});if(!(t.fadeStart>=0)||!(t.fadeEnd>t.fadeStart))throw new y(`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 y(`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 y(`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 y(`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(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Foliage3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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 $i}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()}_syncObject3D(){super._syncObject3D(),this.rebuildIfNeeded();let e=this.pivot;if(this.isShaderField){e.matrix.identity();let t=this.bladesMaterial.uniforms;t.time&&(t.time.value=this.time),t.windStrength&&(t.windStrength.value=this.sway*(this.isMesh?pC:lC)),(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));let n=this.benderSlots;for(let e=0;e<4;e++){let t=this.pickedBenders[e];t?n[e]?.set(t.x,t.y,t.z,t.radius):n[e]?.set(0,0,0,0)}}else if(this.isTufts)e.matrix.identity(),this.tuftTime&&(this.tuftTime.value=this.time),this.tuftStrength&&(this.tuftStrength.value=this.sway*EC);else if(this.sway>0){let t=Math.sin(this.time*1.7)*cC*this.sway,n=Math.sin(this.time*1.3+1.7)*cC*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]=uS(this);this.drape&&!this.drapeTerrain&&this.resolveDrape();let r=this.drapeTerrain,i=[];for(let e of BS(this)){let n=r?r.heightAt(e.x,e.z):t,a=e.footY-n;a<=jC&&a>=-2.5&&i.push({x:e.x,y:e.y,z:e.z,radius:e.radius+AC})}return DS(i,{x:e,z:n,areaX:this.area[0]??0,areaZ:this.area[1]??0})}rebuildIfNeeded(){this.pivot||(this.pivot=new $i,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?dC:this.isTufts?SC: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)lS(e),this.pivot.add(e)}resolveDrape(){if(this.drapeTerrain=null,!this.drape)return;let e=dS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=uS(this);else if(this.terrain!==``)throw new y(`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}buildMeshField(e){let t=Wx({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*dC}),n=this.coverage>=1?t:t.filter(e=>Ux(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 xi(0,0,0,0));let s=Qs.merge([J.lights,J.fog]);Object.assign(s,{time:{value:0},windStrength:{value:this.sway*pC},topColor:{value:new W(this.colorB)},bottomColor:{value:new W(this.colorA)},groundColor:{value:new W(this.groundColor)},sunDirection:{value:new V(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 tc({vertexShader:NS,fragmentShader:PS,uniforms:s,fog:!0,lights:!0,side:2});let c=kS(fC),l=a.length,u=Math.max(l,1),d=new is(c,this.bladesMaterial,u);d.count=l,d.receiveShadow=!0;let f=new b(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=Fx(t.x,t.z),r=Vx(t.x,t.z,this.seed),i=(r-.55)/1.15,o=f.range(mC[0],mC[1]),s=this.height*r*(.55+t.scale*.6);RC.set(t.x,this.bedY(t.x,t.z),t.z),zC.setFromAxisAngle(IC,t.rotY),BC.set(o,s,o),d.setMatrixAt(e,LC.compose(RC,zC,BC));let c=n.leanDir+f.range(-.6,.6),l=(hC+gC*(.5*n.lean+.5*f.next()))*(1+vC*i);p[e*4]=Math.cos(c)*l,p[e*4+1]=Math.sin(c)*l,p[e*4+2]=f.range(_C[0],_C[1])*(1+yC*i),p[e*4+3]=f.next(),m[e]=n.hue;let u=Hx(t.x,t.z,this.seed)*.85+(f.next()-.5)*.3;h[e]=Math.min(1,Math.max(0,u))}c.setAttribute(`aBlade`,new Xo(p,4)),c.setAttribute(`aClumpHue`,new Xo(m,1)),c.setAttribute(`aDry`,new Xo(h,1)),d.instanceMatrix.needsUpdate=!0,this.meshes=[d],o.length>0&&this.meshes.push(this.buildFlowerMesh(o))}buildFlowerMesh(e){let t=new is(AS(bC),new rc({roughness:1,side:2}),Math.max(e.length,1));t.count=e.length,t.receiveShadow=!0;let n=new b(this.seed+15797765);for(let r=0;r<e.length;r++){let i=e[r],a=Vx(i.x,i.z,this.seed),o=this.height*a*(.85+n.next()*.35);RC.set(i.x,this.bedY(i.x,i.z),i.z),zC.setFromAxisAngle(IC,i.rotY),BC.set(1,o,1),t.setMatrixAt(r,LC.compose(RC,zC,BC));let s=n.next(),c=xC[s<.45?0:s<.75?1:2];t.setColorAt(r,UC.set(c))}return t.instanceMatrix.needsUpdate=!0,t.instanceColor&&(t.instanceColor.needsUpdate=!0),t}buildTuftField(e){let t=Wx({seed:this.seed,areaX:this.area[0]??0,areaZ:this.area[1]??0,count:e,density:this.density*SC}),n=this.coverage>=1?t:t.filter(e=>Ux(e.x,e.z,this.seed)<=this.coverage);this.tuftTime={value:this.time},this.tuftStrength={value:this.sway*EC};let r=new rc({alphaTest:.5,side:2,roughness:1}),i=KS(this.seed,this.tuftStyle);i&&(r.map=i,this.tuftTexture=i),nC(r,this.tuftTime,this.tuftStrength);let a=new is(PC(),r,Math.max(n.length,1));a.count=n.length,a.castShadow=!1,a.receiveShadow=!0;let o=new b(this.seed+7403357),s=VC.set(this.colorA),c=HC.set(this.colorB);for(let e=0;e<n.length;e++){let t=n[e],r=1+(Vx(t.x,t.z,this.seed)-1)*TC,i=this.height*CC*r*o.range(DC[0],DC[1]),l=i*wC*o.range(OC[0],OC[1]);RC.set(t.x,this.bedY(t.x,t.z),t.z),zC.setFromAxisAngle(IC,t.rotY),BC.set(l,i,l),a.setMatrixAt(e,LC.compose(RC,zC,BC));let u=Fx(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,Hx(t.x,t.z,this.seed)*.8-.1));UC.copy(s).lerp(c,d).lerp(WC.set(kC),f*.5).multiplyScalar(o.range(.62,1.18)),a.setColorAt(e,UC)}a.instanceMatrix.needsUpdate=!0,a.instanceColor&&(a.instanceColor.needsUpdate=!0),this.meshes=[a]}buildBladesField(e){let t=Wx({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 xi(0,0,0,0));let n=Qs.merge([J.fog]);Object.assign(n,{time:{value:0},windStrength:{value:this.sway*lC},topColor:{value:new W(this.colorB)},bottomColor:{value:new W(this.colorA)},grassHeight:{value:this.height},grassScale:{value:1},benders:{value:this.benderSlots}}),this.bladesMaterial=new tc({vertexShader:jS,fragmentShader:MS,uniforms:n,fog:!0,transparent:!0,side:2,depthWrite:!0,depthTest:!0,alphaTest:.1,blending:0});let r=NC(this.height),i=new is(r,this.bladesMaterial,Math.max(e,1)),a=new is(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];RC.set(e.x,this.bedY(e.x,e.z),e.z),BC.setScalar(e.scale),zC.setFromAxisAngle(IC,e.rotY),i.setMatrixAt(n,LC.compose(RC,zC,BC)),zC.setFromAxisAngle(IC,e.rotY+Math.PI/2),a.setMatrixAt(n,LC.compose(RC,zC,BC))}i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,this.meshes=[i,a]}buildSimpleField(e){let t=new rc({side:2,roughness:1}),n=new is(FC(oC[this.kind]??.08),t,Math.max(e,1));n.count=e,n.receiveShadow=!0;let r=new b(this.seed),i=(this.area[0]??0)/2,a=(this.area[1]??0)/2,o=VC.set(this.colorA),s=HC.set(this.colorB);for(let t=0;t<e;t++){let e=r.range(-i,i),c=r.range(-a,a);RC.set(e,this.bedY(e,c),c),zC.setFromAxisAngle(IC,r.range(0,Math.PI*2)),BC.set(1,this.height*r.range(sC[0],sC[1]),1),LC.compose(RC,zC,BC),n.setMatrixAt(t,LC),n.setColorAt(t,UC.copy(o).lerp(s,r.next()))}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 NC(e){let t=new Gs(1,e,1,1);return t.translate(0,e/2,0),t}function PC(){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 K;return i.setAttribute(`position`,new G(new Float32Array(e),3)),i.setAttribute(`normal`,new G(new Float32Array(t),3)),i.setAttribute(`uv`,new G(new Float32Array(n),2)),i.setIndex(r),i}function FC(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 K;return i.setAttribute(`position`,new G(n,3)),i.setAttribute(`normal`,new G(r,3)),i.setIndex([0,1,2,2,1,3,4,5,6,6,5,7]),i}var IC=new V(0,1,0),LC=new U,RC=new V,zC=new B,BC=new V,VC=new W,HC=new W,UC=new W,WC=new W,GC=class extends Dy{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 rl}_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}}},KC=class extends Dy{static typeName=`OmniLight3D`;static props={color:{default:`#ffffff`},intensity:{default:1},range:{default:0}};color=`#ffffff`;intensity=1;range=0;_createObject3D(){return new el}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();e.color.set(this.color),e.intensity=this.intensity,e.distance=this.range}},qC=[`color`,`metalness`,`roughness`,`emissive`,`emissiveIntensity`,`wireframe`,`flatShading`,`opacity`,`clearcoat`,`clearcoatRoughness`,`envMapIntensity`,`depthTest`,`depthWrite`,`map`,`normalMap`,`repeat`],JC=class extends Dy{static typeName=`MeshInstance3D`;static props={mesh:{default:`box`,options:[`box`,`sphere`,`capsule`,`plane`,`cylinder`,`gem`]},size:{default:[1,1,1]},material:{default:{}},castShadow:{default:!1},receiveShadow:{default:!1}};mesh=`box`;size=[1,1,1];material={};castShadow=!1;receiveShadow=!1;static validateJson(e){XC(e.material,e.name)}geometryKey=``;textureKey=``;loadedTextures=[];_createObject3D(){return new Mo(new zs(1,1,1),new ic)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D(),t=`${this.mesh}:${JSON.stringify(this.size)}`;t!==this.geometryKey&&(e.geometry.dispose(),e.geometry=ZC(this.mesh,this.size),this.geometryKey=t);let n=e.material;YC(n,this.material),this.syncTextures(n),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}syncTextures(e){let t=JSON.stringify([this.material.map??``,this.material.normalMap??``,this.material.repeat??null]);if(t===this.textureKey)return;this.textureKey=t;for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[];let n=e.map!==null||e.normalMap!==null;e.map=null,e.normalMap=null;let r=typeof document<`u`?new Lc:null;r&&this.material.map&&(e.map=this.loadTexture(r,this.material.map,!0)),r&&this.material.normalMap&&(e.normalMap=this.loadTexture(r,this.material.normalMap,!1)),(n||e.map||e.normalMap)&&(e.needsUpdate=!0)}loadTexture(e,t,n){let r=e.load(t);r.wrapS=Lt,r.wrapT=Lt;let[i,a]=this.material.repeat??[1,1];return r.repeat.set(i,a),r.anisotropy=4,n&&(r.colorSpace=fr),this.loadedTextures.push(r),r}free(){for(let e of this.loadedTextures)e.dispose();this.loadedTextures=[],super.free()}};function YC(e,t){e.color.set(t.color??`#ffffff`),e.metalness=t.metalness??0,e.roughness=t.roughness??1,e.wireframe=t.wireframe??!1,e.emissive.set(t.emissive??`#000000`),e.emissiveIntensity=t.emissiveIntensity??1;let n=t.opacity??1;e.opacity=n,e.transparent=n<1;let r=t.clearcoat??0;e.clearcoat>0!=r>0&&(e.needsUpdate=!0),e.clearcoat=r,e.clearcoatRoughness=t.clearcoatRoughness??0,e.envMapIntensity=t.envMapIntensity??1,e.depthTest=t.depthTest??!0,e.depthWrite=t.depthWrite??!0;let i=t.flatShading??!1;e.flatShading!==i&&(e.flatShading=i,e.needsUpdate=!0)}function XC(e,t,n=`MeshInstance3D`){let r=e=>{throw new y(`BAD_FORMAT`,`${n} '${t}' ${e}`,{prop:`material`,validOptions:[...qC]})};(typeof e!=`object`||!e||Array.isArray(e))&&r(`material must be an object, got ${JSON.stringify(e)}.`);for(let t of Object.keys(e))qC.includes(t)||r(`material has unknown key '${t}' — must be one of [${qC.join(`, `)}].`);for(let t of[`map`,`normalMap`]){let n=e[t];n!==void 0&&(typeof n!=`string`||n.length===0)&&r(`material.${t} must be a non-empty texture URL string, got ${JSON.stringify(n)}.`)}if(e.repeat!==void 0){let t=e.repeat;(!Array.isArray(t)||t.length!==2||!t.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0))&&r(`material.repeat must be [u, v] with positive numbers, got ${JSON.stringify(t)}.`),!e.map&&!e.normalMap&&r(`material.repeat tiles nothing — add a 'map' and/or 'normalMap' texture URL.`)}for(let t of[`metalness`,`roughness`,`opacity`,`clearcoat`,`clearcoatRoughness`]){let n=e[t];n!==void 0&&!(typeof n==`number`&&n>=0&&n<=1)&&r(`material.${t} must be a number in 0..1, got ${JSON.stringify(n)}.`)}e.envMapIntensity!==void 0&&!(typeof e.envMapIntensity==`number`&&Number.isFinite(e.envMapIntensity)&&e.envMapIntensity>=0)&&r(`material.envMapIntensity must be a number >= 0, got ${JSON.stringify(e.envMapIntensity)}.`);for(let t of[`wireframe`,`flatShading`,`depthTest`,`depthWrite`]){let n=e[t];n!==void 0&&typeof n!=`boolean`&&r(`material.${t} must be a boolean, got ${JSON.stringify(n)}.`)}}function ZC(e,t){let n=t[0]??1,r=t[1]??1,i=t[2]??1;switch(e){case`box`:return new zs(n,r,i);case`sphere`:return new Ks(n,32,16);case`gem`:return new Ws(n,0);case`capsule`:return new Bs(n,r,8,16);case`plane`:{let e=new Gs(n,i);return e.rotateX(-Math.PI/2),e}case`cylinder`:return new Vs(n,n,r,24);default:throw new y(`PROP_TYPE_MISMATCH`,`MeshInstance3D.mesh must be one of box|sphere|capsule|plane|cylinder|gem, got '${e}'.`)}}var QC=class extends Dy{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;$C(t.sections,e.name),XC(t.material,e.name,`LoftMesh3D`);for(let n of[`map`,`normalMap`,`repeat`])if(t.material[n]!==void 0)throw new y(`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 Mo(new K,new ic)}_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=nw(this.sections,this.slices,this.smooth),this.geometryKey=t),YC(e.material,this.material),e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow}};function $C(e,t){let n=e=>{throw new y(`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 ew(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 tw(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:ew(a.z,o.z,s.z,c.z,n),width:Math.max(1e-4,ew(a.width,o.width,s.width,c.width,n)),height:Math.max(1e-4,ew(a.height,o.height,s.height,c.height,n)),y:ew(a.y,o.y,s.y,c.y,n),corner:Math.min(1,Math.max(0,ew(a.corner,o.corner,s.corner,c.corner,n)))})}}return r}function nw(e,t,n){let r=Math.max(8,Math.min(64,Math.round(t))),i=tw(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 K;return d.setAttribute(`position`,new G(o,3)),d.setIndex(l),d.computeVertexNormals(),d}var rw={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`},iw={};for(let[e,t]of Object.entries(rw))iw[`mixamorig${e}`]=t,iw[`mixamorig:${e}`]=t;function aw(e,t,n){let r=[],i=new Set,a=new B,o=new B,s=new B,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 V).y)/Math.max(1e-6,Math.abs(l.getWorldPosition(new V).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=iw[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 xc&&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 xc(`${m}.quaternion`,[...l.times],[...e]))}else if(l instanceof Cc&&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 Cc(`${m}.position`,[...l.times],[...e]))}}return{clip:new wc(`${e.name} (VRM)`,e.duration,r),retargetedTracks:r.length,skippedBones:[...i]}}var ow=.2,sw=class extends Dy{static typeName=`ModelInstance3D`;static signals=[`animationFinished`];static props={...Dy.props,model:{default:``},animation:{default:``},targetHeight:{default:0},castShadow:{default:!1},animationLoop:{default:!0},receiveShadow:{default:!1},tint:{default:``},metalness:{default:-1},roughness:{default:-1}};model=``;animation=``;targetHeight=0;castShadow=!1;animationLoop=!0;receiveShadow=!1;tint=``;metalness=-1;roughness=-1;store=null;entry=null;mountedRef=``;fittedHeight=-1;fitGroup=null;mixer=null;playing=``;currentAction=null;actionKeys=new WeakMap;warnedClaim=!1;tintTargets=[];tintedClones=[];appliedMods=``;nodePoses=new Map;poseNode(e,t){this.nodePoses.set(e,t),this.applyPoses()}_createObject3D(){return new $i}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,console.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=_v(n.scene);let r=new $i;r.add(e),t.add(r),this.fitGroup=r,this.entry=n,this.mountedRef=this.model,this.mixer=new Dl(e),this.mixer.addEventListener(`finished`,e=>{let t=e.action,n=(t&&this.actionKeys.get(t))??this.animation;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=cw(this.fitGroup).getSize(new V),n=t.y>0?this.targetHeight/t.y:e;n<.05||n>20?(this.fitGroup.scale.setScalar(1),console.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)}}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 W(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)}}syncAnimation(e){if(!this.mixer||!this.entry||this.playing===this.animation)return;if(this.animation===``){this.currentAction&&this.currentAction.fadeOut(ow),this.currentAction=null,this.playing=``;return}let t=this.entry.animations.find(e=>e.name===this.animation)??null;if(!t&&(this.animation.startsWith(`$`)||/\.(glb|gltf)$/i.test(this.animation))){let n=e.getAnimation(this.animation);if(n.status===`loading`)return;if(n.status===`ready`&&n.scene){let e=(n.clip?n.clips.find(e=>e.name===n.clip):void 0)??n.clips[0];if(e)if(this.entry.isVrm&&this.entry.vrm){let r=this.entry.retargeted.get(this.animation);if(r)t=r;else{let r=aw(e,n.scene,this.entry.vrm);r.skippedBones.length>0&&console.warn(`incanto: retarget '${this.animation}' skipped bones: ${r.skippedBones.join(`, `)}`),this.entry.retargeted.set(this.animation,r.clip),t=r.clip}}else t=e}}if(this.playing=this.animation,t){let e=this.mixer.clipAction(t);if(e.reset(),this.animationLoop?e.setLoop($n,1/0):(e.setLoop(Qn,1),e.clampWhenFinished=!0),e.setEffectiveWeight(1),e.play(),this.actionKeys.set(e,this.animation),this.currentAction&&this.currentAction!==e){let n=t.duration>0&&this.currentAction.getClip().duration>0;e.crossFadeFrom(this.currentAction,ow,n)}this.currentAction=e}else console.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)`}`)}update(e){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.entry=null,this.mountedRef=``,this.playing=``,this.fittedHeight=-1}};function cw(e){e.updateWorldMatrix(!0,!0);let t=new Ca,n=new Ca,r=e.matrixWorld.clone().invert(),i=new U,a=new V;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 lw=.01,uw=class e extends Dy{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`,...at]},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`&&!at.includes(t.preset))throw new y(`BAD_FORMAT`,`Particles3D '${e.name}' preset must be 'custom' or one of [${at.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:at});if(t.blend!==`add`&&t.blend!==`normal`)throw new y(`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){ot(this,this.preset,ge(e.typeName));let t=this.tree?.engine?.rng??new b(4660);this.sim=new ct({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[(this.speed[0]??0)*lw,(this.speed[1]??0)*lw],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[(this.gravity[0]??0)*lw,(this.gravity[1]??0)*lw,(this.gravity[2]??0)*lw],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 W,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 K;e.setAttribute(`position`,new G(this.positions,3)),e.setAttribute(`color`,new G(this.colors,4));let t=new Ds({size:(this.sizeStart+this.sizeEnd)/2*lw,map:hw(),vertexColors:!0,transparent:!0,depthWrite:!1,depthTest:this.depthTest,alphaTest:.02,sizeAttenuation:!0,blending:this.blend===`add`?2:1});this.points=new Ms(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:dw.set(this.colorStart),o=fw.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))),pw.copy(t).lerp(o,e.t),r[c*4]=pw.r,r[c*4+1]=pw.g,r[c*4+2]=pw.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}},dw=new W,fw=new W,pw=new W,mw=null;function hw(){if(mw)return mw;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 Ko(t,64,64,cn);return n.magFilter=Ut,n.minFilter=Ut,n.generateMipmaps=!1,n.needsUpdate=!0,mw=n,n}var gw=128,_w=class extends Dy{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 $i,t=new K;t.setAttribute(`position`,new G(new Float32Array(gw*2*3),3));let n=new bo({color:this.color,transparent:!0,opacity:this.opacity,side:2,depthWrite:!1,blending:this.additive?2:1});return this.mesh=new Mo(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(vw);let e=this.points[this.points.length-1];(!e||(e.x-vw.x)**2+(e.y-vw.y)**2+(e.z-vw.z)**2>this.minDistance*this.minDistance)&&(this.points.push({x:vw.x,y:vw.y,z:vw.z,t:this.clock}),this.points.length>gw&&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 W(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;yw.set(r.x-n.x,r.y-n.y,r.z-n.z),yw.lengthSq()<1e-8&&yw.set(0,1,0),bw.set(e.camera.position.x-n.x,e.camera.position.y-n.y,e.camera.position.z-n.z),xw.crossVectors(yw,bw).normalize();let a=(this.clock-n.t)/this.seconds,s=this.width/2*Math.max(0,1-a);o.setXYZ(t*2,n.x+xw.x*s,n.y+xw.y*s,n.z+xw.z*s),o.setXYZ(t*2+1,n.x-xw.x*s,n.y-xw.y*s,n.z-xw.z*s)}if(o.needsUpdate=!0,!a.index||a.index.count<(gw-1)*6){let e=[];for(let t=0;t<gw-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}},vw=new V,yw=new V,bw=new V,xw=new V;function Sw(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 Cw={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}}},ww=[`ash`,`aspen`,`oak`,`pine`,`bush`,`ash-forest`,`oak-forest`,`pine-forest`,`bush-forest`];function Tw(e){let t=Cw[e];if(!t)throw new y(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${ww.join(`, `)}].`,{prop:`preset`,validOptions:ww});return structuredClone(t)}var Ew={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 Dw(e){if(!ww.includes(e))throw new y(`BAD_FORMAT`,`Unknown eztree preset '${e}' — must be one of [${ww.join(`, `)}].`,{prop:`preset`,validOptions:ww});return structuredClone(Ew[e.replace(/-forest$/,``)])}var Ow=.45,kw=.45,Aw=.55,jw=.15,Mw=.07,Nw=.035;function Pw(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 Fw(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,kw);x=(r-f)/e*t,S=kw*t,C=(l-m)/e*t}let t=(c-s)/Math.max(u-s,.001),n=Math.max(jw,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-Aw)+e/i*Aw,S=S*(1-Aw)+t/i*Aw,C=C*(1-Aw)+n/i*Aw;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=Ow+(1-Ow)*w,D=t[o],O=E*(1-Mw*Pw(D,1)),k=(Pw(D,2)-.5)*2*Nw;a[o*3]=O*(1+k),a[o*3+1]=O,a[o*3+2]=O*(1-k)}return{normals:i,colors:a}}var Iw=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 Lw(e,t,n){let r=new Iw(t),i={branchVerts:[],branchNormals:[],branchUvs:[],branchIndices:[],leafVerts:[],leafIndices:[],leafUvs:[],leafAnchors:[],leafClusters:[],leafClusterNext:0},a=[{origin:new V,orientation:new Fi,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;)Rw(e,r,i,a,a.shift());Gw(i,n);let o=new K;o.setAttribute(`position`,new G(new Float32Array(i.branchVerts),3)),o.setAttribute(`normal`,new G(new Float32Array(i.branchNormals),3)),o.setAttribute(`uv`,new G(new Float32Array(i.branchUvs),2)),o.setIndex(new G(Kw(i.branchIndices,i.branchVerts),1)),o.computeBoundingSphere();let s=null;if(i.leafVerts.length>0){s=new K,s.setAttribute(`position`,new G(new Float32Array(i.leafVerts),3)),s.setAttribute(`anchor`,new G(new Float32Array(i.leafAnchors),3)),s.setAttribute(`uv`,new G(new Float32Array(i.leafUvs),2)),s.setIndex(new G(Kw(i.leafIndices,i.leafVerts),1));let t=Fw(i.leafVerts,i.leafClusters,e.type);s.setAttribute(`normal`,new G(t.normals,3)),s.setAttribute(`color`,new G(t.colors,3)),s.computeBoundingSphere()}return{branches:o,leaves:s}}function Rw(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 V,d=new V,f=0;for(let e=0;e<i.segmentCount;e++){let t=2*Math.PI*e/i.segmentCount,c=new V(Math.cos(t),0,Math.sin(t)).multiplyScalar(a).applyEuler(o).add(s),l=new V(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 V(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 B().setFromEuler(o),h=new B().setFromAxisAngle(new V(0,1,0),e.branch.twist[i.level]??0),g=e.branch.force,_=new B().setFromUnitVectors(new V(0,1,0),new V(g.direction.x,g.direction.y,g.direction.z));m.multiply(h),m.rotateTowards(_,g.strength/a),o.setFromQuaternion(m)}Ww(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&&Uw(e,t,n,a.origin,a.orientation,u)}i.level===e.branch.levels?Hw(e,t,n,l,u):i.level<e.branch.levels&&Vw(e,t,r,e.branch.children[i.level]??0,i.level+1,l)}function zw(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 V().lerpVectors(r.origin,i.origin,a),s=new B().setFromEuler(r.orientation),c=new B().setFromEuler(i.orientation);return{origin:o,orientation:new Fi().setFromQuaternion(c.slerp(s,a)),radius:{a:r.radius,b:i.radius,alpha:a}}}function Bw(e,t,n){let r=new B().setFromAxisAngle(new V(1,0,0),t/(180/Math.PI)),i=new B().setFromAxisAngle(new V(0,1,0),n),a=new B().setFromEuler(e);return new Fi().setFromQuaternion(a.multiply(i.multiply(r)))}function Vw(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=zw(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=Bw(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 Hw(e,t,n,r,i){let a=t.random();for(let o=0;o<e.leaves.count;o++){let s=zw(r,t.random(1,e.leaves.start)),c=2*Math.PI*(a+o/e.leaves.count),l=Bw(s.orientation,e.leaves.angle,c);Uw(e,t,n,s.origin,l,i)}}function Uw(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 V(-t,s,0),new V(-t,0,0),new V(t,0,0),new V(t,s,0)];for(let t of c)t.applyEuler(new Fi(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 Ww(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 Gw(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 Kw(e,t){return t.length/3>65535?new Uint32Array(e):new Uint16Array(e)}var qw=[`simple`,`medium`,`high`],Jw=[`conifer`,`broadleaf`,`dead`,`bush`];function Yw(e,t,n){return new y(`BAD_FORMAT`,`Tree3D ${e} must be one of [${n.join(`, `)}], got '${t}'.`,{prop:e,validOptions:n})}var Xw={simple:0,medium:1,high:2},Zw=[5,7,10],Qw=[2,3,4],$w=[6,8,12],eT=[2,3,3],tT=[0,1,2],nT=[3,4,5],rT=3;function iT(e,t){if(!qw.includes(e))throw Yw(`tier`,e,qw);if(!Jw.includes(t))throw Yw(`type`,t,Jw);let n=e,r=t,i=Xw[n];return{tier:n,type:r,trunkRadialSegments:Zw[i],canopyLayers:r===`conifer`?Qw[i]:0,canopySegments:$w[i],blobCount:r===`broadleaf`||r===`bush`?eT[i]:0,blobDetail:tT[i],branchCount:r===`dead`?nT[i]:r===`conifer`&&n===`high`?rT:0,hasCanopy:r!==`dead`,canopySway:n!==`simple`}}var aT=.02,oT={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 sT(e,t,n){let{trunkHeight:r,trunkRadiusBottom:i,trunkRadiusTop:a}=oT[e.type],o=[],s=new Vs(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 Vs(.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 U().makeRotationY(c).multiply(new U().makeRotationX(s)).setPosition(Math.sin(c)*i*.6,l,Math.cos(c)*i*.6)),o.push(a)}let c=lT(o);return dT(c,new W(n),.7,1.05,t),c}function cT(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 Hs(o,s,e.canopySegments).toNonIndexed();uT(c,t,aT),c.translate(0,.26+n*a+s/2,0),r.push(c)}for(let n=0;n<e.branchCount;n++){let i=new Hs(.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 U().makeRotationY(a).multiply(new U().makeRotationX(o)).setPosition(Math.sin(a)*.22,.34+t.next()*.18,Math.cos(a)*.22)),r.push(i)}}else{let{trunkHeight:n}=oT[e.type];for(let i=0;i<e.blobCount;i++){let a=new Ws((i===0?.3:.24-i*.02)*(.92+t.next()*.16),e.blobDetail).toNonIndexed();a.scale(1,.72,1),uT(a,t,aT);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=lT(r);return dT(i,new W(n),.62,1.18,t),i}function lT(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 K;return a.setAttribute(`position`,new G(n,3)),a.setAttribute(`normal`,new G(r,3)),a}function uT(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 dT(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 W;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 G(o,3))}var fT=500,pT=15e5,mT=[.8,1.2],hT=.28,gT=.12,_T=.055,vT=.11,yT=3,bT=101,xT=[.78,.7,.45],ST=.45,CT=.55,wT=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation`,TT=`https://agent8-games.verse8.io/assets/3D/default/textures/vegetation/bark`,ET={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`]}},DT=class e extends Dy{static typeName=`Tree3D`;static props={tier:{default:`medium`,options:qw},type:{default:`conifer`,options:Jw},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:!1},terrain:{default:``}};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=!1;terrain=``;drapeTerrain=null;drapeWorld=[0,0,0];static validateJson(e){let t=e;if(iT(t.tier,t.type),!(t.height>0))throw new y(`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>fT)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' count must be an integer in 1..${fT}, got ${t.count}.`,{prop:`count`});if(!((t.area[0]??0)>0)||!((t.area[1]??0)>0))throw new y(`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 y(`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 y(`BAD_FORMAT`,`Tree3D '${e.name}' leafShadows must be a boolean, got ${JSON.stringify(t.leafShadows)}.`,{prop:`leafShadows`});if(typeof t.drape!=`boolean`)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' drape must be a boolean, got ${JSON.stringify(t.drape)}.`,{prop:`drape`});if(typeof t.terrain!=`string`)throw new y(`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=AT(t.tier,t.type),r=n*t.count;if(r>pT)throw new y(`BAD_FORMAT`,`Tree3D '${e.name}' blows the grove triangle budget: count ${t.count} × ${n} tris/tree (tier '${t.tier}', type '${t.type}') = ${r} > ${pT}. Lower count (max ${Math.floor(pT/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 $i}_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 $i,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)return;let e=dS(this,this.terrain);if(e)this.drapeTerrain=e,this.drapeWorld=uS(this);else if(this.terrain!==``)throw new y(`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=iT(this.tier,this.type),t=new b(this.seed),n=sT(e,t,this.trunkColor),r=cT(e,t,this.canopyColor),i=new is(n,IT(),this.count);RT(i);let a=null;r&&(a=new is(r,IT(),this.count),RT(a)),this.scatter(t,(e,t,n)=>{i.setMatrixAt(e,t),i.setColorAt(e,n),a?.setMatrixAt(e,t),a?.setColorAt(e,n)}),LT(i),a&&LT(a),this.simpleTrunk=i,this.simpleCanopy=a,this.grove.add(i),a&&this.grove.add(a)}buildEzGrove(){let e=ET[this.tier][this.type],t=Math.min(yT,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=NT(this.canopyColor),i=null;typeof document<`u`&&typeof createImageBitmap==`function`&&(i=new sl,i.setOptions({imageOrientation:`flipY`}));for(let a=0;a<t;a++){let t=n[a],o=e[a],s=Tw(o);this.type===`dead`&&(s.leaves.count=0);let c=Lw(s,this.seed+a*bT,1),l=this.buildBarkMaterial(o,i),u=new is(c.branches,l,t);RT(u);let d=null;if(c.leaves){let e=new rc({color:r.clone().multiply(new W(xT[0],xT[1],xT[2])),roughness:1,side:2,vertexColors:!0,alphaTest:s.leaves.alphaTest}),n=this.leafTexture||jT(s.leaves.style);i&&(e.map=kT(i,n,e=>{e.colorSpace=fr,e.flipY=!1},e=>MT(e))),$S(e,this.swayUniform,ST,this.leafFadeUniform??void 0),d=new is(c.leaves,e,t),RT(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 b(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)LT(e.branches),e.leaves&&LT(e.leaves)}buildBarkMaterial(t,n){if(this.type===`dead`||!n)return new rc({color:new W(this.trunkColor),roughness:1});let r=Dw(t),i=new rc({color:this.trunkColor===e.props.trunkColor?.default?new W(r.tint):FT(this.trunkColor),roughness:1});return QS(i,CT),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 kT(e,`${TT}/${t.texture}_${n}_1k.jpg`,e=>{e.wrapS=Lt,e.wrapT=Lt,e.repeat.set(t.repeat[0],t.repeat[1]),e.anisotropy=4,e.flipY=!1,r&&(e.colorSpace=fr)})}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);VT.set(a,this.drape?this.bedY(a,o):0,o),HT.setFromAxisAngle(zT,e.range(0,Math.PI*2));let s=this.height*e.range(mT[0],mT[1]),c=s*e.range(.9,1.1);UT.set(c,s,c),BT.compose(VT,HT,UT),WT.setHSL(hT,gT,.92).offsetHSL(e.range(-.055,_T),0,e.range(-.11,vT)),t(i,BT,WT)}}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()}},OT=new Map;function kT(e,t,n,r){let i=OT.get(t);if(i)return i;let a=new bi;return n(a),e.load(t,e=>{a.image=e,r?r(a):a.needsUpdate=!0}),OT.set(t,a),a}function AT(e,t){let n=0;for(let r of new Set(ET[e][t]??[])){let e=Tw(r);t===`dead`&&(e.leaves.count=0),n=Math.max(n,Sw(e).total)}return n}function jT(e){return`${wT}/${e}_color.png`}function MT(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 NT(e){let t=new W(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t.lerp(PT,.18)}var PT=new W(1,1,1);function FT(e){let t=new W(e),n=Math.max(t.r,t.g,t.b);return n>0?t.multiplyScalar(1/n):t.setRGB(1,1,1),t}function IT(){return new rc({vertexColors:!0,roughness:1,flatShading:!0})}function LT(e){e.instanceMatrix.needsUpdate=!0,e.instanceColor&&(e.instanceColor.needsUpdate=!0),lS(e)}function RT(e){e.castShadow=!0,e.receiveShadow=!0}var zT=new V(0,1,0),BT=new U,VT=new V,HT=new B,UT=new V,WT=new W,GT=[[[.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]]],KT=2e5,qT=class extends Dy{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 zs(1,1,1),t=new tc({vertexShader:YT,fragmentShader:XT});this.mesh=new is(e,t,KT),this.mesh.count=0,this.mesh.frustumCulled=!1;for(let e of JT)this.mesh.geometry.setAttribute(e,new Xo(new Float32Array(KT*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 U,t=0;for(let[n,r]of this.map){if(t>=KT)break;let[i,a,o]=n.split(`,`).map(Number);e.setPosition(i,a,o),this.mesh.setMatrixAt(t,e);let s=GT[r]??GT[0];for(let e=0;e<6;e++){let n=this.mesh.geometry.getAttribute(JT[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}},JT=[`colorFront`,`colorRight`,`colorBack`,`colorLeft`,`colorTop`,`colorBottom`],YT=`
5825
5825
  attribute vec3 colorFront;
5826
5826
  attribute vec3 colorRight;
5827
5827
  attribute vec3 colorBack;
@@ -5842,7 +5842,7 @@ void main() {
5842
5842
  if (abs(n.x) > 0.5) vUv2 = p.zy; else if (abs(n.y) > 0.5) vUv2 = p.xz; else vUv2 = p.xy;
5843
5843
  gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0);
5844
5844
  }
5845
- `,HT=`
5845
+ `,XT=`
5846
5846
  varying vec3 vColor;
5847
5847
  varying vec3 vNormal;
5848
5848
  varying vec2 vUv2;
@@ -5853,7 +5853,7 @@ void main() {
5853
5853
  if (vUv2.x < edge || vUv2.x > 1.0 - edge || vUv2.y < edge || vUv2.y > 1.0 - edge) color *= 0.75;
5854
5854
  gl_FragColor = vec4(color, 1.0);
5855
5855
  }
5856
- `,UT=new fs,WT=new U,GT=new Qa;function KT(e,t,n){return WT.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),UT.setFromProjectionMatrix(WT),GT.center.set(t.x,t.y,t.z),GT.radius=n,UT.intersectsSphere(GT)}function qT(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 JT(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function YT(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 XT(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 ZT(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 QT(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 $T(e,t,n){let r=0;for(let i of n)r+=QT(e,t,i);return r}function eE(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 tE=`
5856
+ `,ZT=new fs,QT=new U,$T=new Qa;function eE(e,t,n){return QT.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),ZT.setFromProjectionMatrix(QT),$T.center.set(t.x,t.y,t.z),$T.radius=n,ZT.intersectsSphere($T)}function tE(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 nE(e){return .55+Math.min(Math.max(e,0),12)/12*.45}function rE(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 iE(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 aE(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 oE(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 sE(e,t,n){let r=0;for(let i of n)r+=oE(e,t,i);return r}function cE(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 lE=`
5857
5857
  precision highp float;
5858
5858
 
5859
5859
  // atmosphere: three's linear fog rides the standard chunks (compiled out
@@ -5877,7 +5877,7 @@ void main() {
5877
5877
  // atmosphere: fog depth from the displaced surface position
5878
5878
  #include <fog_vertex>
5879
5879
  }
5880
- `,nE=`
5880
+ `,uE=`
5881
5881
  precision highp float;
5882
5882
 
5883
5883
  // atmosphere: standard fog chunk (compiled out without scene fog)
@@ -6072,7 +6072,7 @@ void main() {
6072
6072
  #include <colorspace_fragment>
6073
6073
  #include <fog_fragment>
6074
6074
  }
6075
- `,rE=`
6075
+ `,dE=`
6076
6076
  precision highp float;
6077
6077
 
6078
6078
  // incanto atmosphere: three's linear fog rides the standard chunks (compiled
@@ -6224,7 +6224,7 @@ void main() {
6224
6224
  vec4 mvPosition = viewMatrix * modelPosition;
6225
6225
  #include <fog_vertex>
6226
6226
  }
6227
- `,iE=`
6227
+ `,fE=`
6228
6228
  precision highp float;
6229
6229
 
6230
6230
  // incanto atmosphere: standard fog chunk (compiled out without scene fog)
@@ -6871,13 +6871,13 @@ void main() {
6871
6871
  #include <colorspace_fragment>
6872
6872
  #include <fog_fragment>
6873
6873
  }
6874
- `;function aE(e,t,n,r,i=0){return t>=r.centerY?!1:Math.abs(e-r.centerX)<=r.halfW+i&&Math.abs(n-r.centerZ)<=r.halfD+i}var oE=22,sE={enabled:!0,color:`#cdeeff`,intensity:.55,scale:.32,speed:1};function cE(e,t){if(e===!1)return{enabled:!1,color:uE(t),visibility:oE,caustics:sE};let n=e&&typeof e==`object`?e:{};return{enabled:!0,color:n.color??uE(t),visibility:n.visibility??oE,caustics:lE(n.caustics)}}function lE(e){if(e===!1)return{...sE,enabled:!1};let t=e&&typeof e==`object`?e:{};return{enabled:!0,color:typeof t.color==`string`?t.color:sE.color,intensity:typeof t.intensity==`number`?t.intensity:sE.intensity,scale:typeof t.scale==`number`?t.scale:sE.scale,speed:typeof t.speed==`number`?t.speed:sE.speed}}function uE(e){let{r:t,g:n,b:r}=dE(e),i=(e,t,n)=>Math.round(e*(1-n)+t*n);return fE(Math.round(i(t,6,.45)*.7),Math.round(i(n,40,.4)*.78),Math.round(i(r,70,.35)*.82))}function dE(e){let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return{r:Number.parseInt(n.slice(0,2),16)||0,g:Number.parseInt(n.slice(2,4),16)||0,b:Number.parseInt(n.slice(4,6),16)||0}}function fE(e,t,n){let r=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,`0`);return`#${r(e)}${r(t)}${r(n)}`}var pE={frequency:6.7,persistence:.3,lacunarity:2.18,iterations:9,speed:.5},mE=.525,hE=.08,gE={freqX:.7,freqZ:.5,cross:.6};function _E(e,t){return e-Math.floor(e/t)*t}function vE(e){return e-Math.floor(e)}function yE(e){return _E((e*34+1)*e,289)}var bE=.211324865405187,xE=.366025403784439,SE=-.577350269189626,CE=.024390243902439;function wE(e,t){let n=Math.floor(e+(e+t)*xE),r=Math.floor(t+(e+t)*xE),i=e-n+(n+r)*bE,a=t-r+(n+r)*bE,o=+(i>a),s=i>a?0:1,c=i+bE-o,l=a+bE-s,u=i+SE,d=a+SE;n=_E(n,289),r=_E(r,289);let f=yE(yE(r)+n),p=yE(yE(r+s)+n+o),m=yE(yE(r+1)+n+1),h=Math.max(.5-(i*i+a*a),0),g=Math.max(.5-(c*c+l*l),0),_=Math.max(.5-(u*u+d*d),0);h*=h,h*=h,g*=g,g*=g,_*=_,_*=_;let v=2*vE(f*CE)-1,y=2*vE(p*CE)-1,b=2*vE(m*CE)-1,x=Math.abs(v)-.5,S=Math.abs(y)-.5,C=Math.abs(b)-.5,w=v-Math.floor(v+.5),T=y-Math.floor(y+.5),E=b-Math.floor(b+.5);h*=1.79284291400159-.85373472095314*(w*w+x*x),g*=1.79284291400159-.85373472095314*(T*T+S*S),_*=1.79284291400159-.85373472095314*(E*E+C*C);let D=w*i+x*a,O=T*c+S*l,ee=E*u+C*d;return 130*(h*D+g*O+_*ee)}function TE(e,t,n,r){let i=Math.max(r.scaleNorm,1e-6),a=e/i,o=t/i,s=0,c=1,l=r.frequency,u=n*r.speed;for(let e=0;e<r.iterations;e++)s+=c*wE(a*l+u,o*l+u),c*=r.persistence,l*=r.lacunarity;return s*r.amplitude}function EE(e,t,n,r){return r*(Math.sin(e*gE.freqX+n)+gE.cross*Math.sin(t*gE.freqZ+n*1.3))}var DE=[`fancy`,`simple`],OE=[`trough`,`surface`,`peak`],kE={trough:`#135a72`,surface:`#2a86a0`,peak:`#a5ddd6`},AE={peakThreshold:.08,peakTransition:.05,troughThreshold:-.01,troughTransition:.15,fresnelScale:1,fresnelPower:5},jE={color:`#dcebe8`,intensity:.32,rangeMin:.45,rangeMax:1.4,scale:.35,edgeColor:`#ffffff`,edgeIntensity:.6,edgeWidth:.5};function ME(e,t){return Math.min(jE.rangeMax,Math.max(jE.rangeMin,Math.min(e,t)*.012))}var NE=128,PE=mE/hE,FE=256,IE=1024,LE=.02,RE=4,zE=32,BE=256,VE=32,HE=.05,UE=.08,WE=.02,GE=.18,KE=.04,qE=1.4,JE=.04,YE=.45,XE=.08,ZE=.4,QE=.22,$E=.09,eD=.85,tD=class e extends Dy{static typeName=`Water3D`;static signals=[`entered`,`exited`];static props={size:{default:[40,40]},color:{default:`#2a6fbe`},opacity:{default:.8},renderOrder:{default:1},waveHeight:{default:.04},waveSpeed:{default:1},quality:{default:`fancy`,options:DE},colors:{default:{}},reflection:{default:!0},reflectionInterval:{default:1e3},foam:{default:!0},interaction:{default:!0},splash:{default:!0},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff5d6`},sunIntensity:{default:1},detailStrength:{default:.26},absorption:{default:.15},refraction:{default:!0},underwater:{default:!0}};size=[40,40];color=`#2a6fbe`;opacity=.8;renderOrder=1;waveHeight=.04;waveSpeed=1;quality=`fancy`;colors={};reflection=!0;reflectionInterval=1e3;foam=!0;interaction=!0;splash=!0;sunDirection=[.5,.8,.3];sunColor=`#fff5d6`;sunIntensity=1;detailStrength=.26;absorption=.15;refraction=!0;underwater=!0;static validateJson(e){let t=e;if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!DE.includes(t.quality))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' quality must be one of [${DE.join(`, `)}], got '${t.quality}'.`,{prop:`quality`,validOptions:DE});for(let[n,r]of Object.entries(t.colors)){if(!OE.includes(n))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' colors has unknown key '${n}'. Valid keys: [${OE.join(`, `)}].`,{prop:`colors`,validOptions:OE});if(typeof r!=`string`)throw new y(`BAD_FORMAT`,`Water3D '${e.name}' colors.${n} must be a hex color string, got ${JSON.stringify(r)}.`,{prop:`colors`})}if(!(t.reflectionInterval>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' reflectionInterval must be > 0 ms, got ${t.reflectionInterval}.`,{prop:`reflectionInterval`});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 y(`BAD_FORMAT`,`Water3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.sunIntensity>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' sunIntensity must be >= 0, got ${t.sunIntensity}.`,{prop:`sunIntensity`});if(!(t.detailStrength>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' detailStrength must be >= 0, got ${t.detailStrength}.`,{prop:`detailStrength`});if(!(t.absorption>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' absorption must be >= 0 (per-meter Beer's-law constant), got ${t.absorption}.`,{prop:`absorption`});let r=t.underwater;if(typeof r!=`boolean`){if(typeof r!=`object`||!r||Array.isArray(r))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater must be true, false or an object ({ color?, visibility? }), got ${JSON.stringify(r)}.`,{prop:`underwater`});let t=r;if(t.color!==void 0&&typeof t.color!=`string`)throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater.color must be a hex color string, got ${JSON.stringify(t.color)}.`,{prop:`underwater`});if(t.visibility!==void 0&&!(t.visibility>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater.visibility must be > 0 meters, got ${JSON.stringify(t.visibility)}.`,{prop:`underwater`})}}time=0;surfaceKey=``;_ripples=[];inWater=new Set;bobTimers=new Map;wadeAnchors=new Map;_scratchA={x:0,y:0,z:0};_scratchB={x:0,y:0,z:0};_bodies=[];cubeTarget=null;cubeCamera=null;reflectionNear=0;lastReflectionAt=0;scenePassTarget=null;_createObject3D(){return new Mo}update(e){this.time+=e*this.waveSpeed,ZT(this._ripples,e),this.interaction&&this.stepInteraction(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildSurfaceIfNeeded(e),this.quality===`simple`?this.syncSimple(e):this.syncFancy(e)}_onRender3D(e){let t=this._ensureObject3D(),n=t.material;if(e.camera.updateWorldMatrix(!0,!1),e.camera.getWorldPosition(fD),this.underwaterAt(fD.x,fD.y,fD.z)||this.quality!==`fancy`||!n.isShaderMaterial)return;let r=Math.hypot((this.size[0]??1)/2,(this.size[1]??1)/2);if(!KT(e.camera,rD(this),r+1))return;let i=n.uniforms,a=Date.now();if(this.reflection){this.cubeTarget||=new pu(FE,{generateMipmaps:!0,minFilter:Gt,type:$t});let n=Math.max((this.size[0]??1)/2,(this.size[1]??1)/2);if((!this.cubeCamera||this.reflectionNear!==n)&&(this.reflectionNear=n,this.cubeCamera=new ul(n,1e3,this.cubeTarget),this.lastReflectionAt=0),this.lastReflectionAt===0||a-this.lastReflectionAt>=this.reflectionInterval){this.lastReflectionAt=a;let n=rD(this),r=this.cubeCamera;r.position.set(n.x,n.y+.1,n.z);let i=t.visible;t.visible=!1,r.update(e.gl,e.scene),t.visible=i}i.uEnvironmentMap&&i.uUseEnvironmentMap&&(i.uEnvironmentMap.value=this.cubeTarget.texture,i.uUseEnvironmentMap.value=1)}e.gl.getDrawingBufferSize(dD);let o=Math.max(1,Math.min(Math.round(dD.x/2),IE)),s=Math.max(1,Math.min(Math.round(dD.y/2),IE));if(this.scenePassTarget&&(this.scenePassTarget.width!==o||this.scenePassTarget.height!==s)&&(this.scenePassTarget.depthTexture?.dispose(),this.scenePassTarget.dispose(),this.scenePassTarget=null),!this.scenePassTarget){let e=new Is(o,s);e.type=Qt,this.scenePassTarget=new Ci(o,s,{depthTexture:e,depthBuffer:!0,stencilBuffer:!1,generateMipmaps:!0,minFilter:Gt})}let c=e.gl.getRenderTarget(),l=e.gl.autoClear,u=e.gl.clippingPlanes,d=t.visible;t.visible=!1;let f=rD(this).y;mD.constant=f+LE,e.gl.clippingPlanes=hD,e.gl.setRenderTarget(this.scenePassTarget),e.gl.autoClear=!0,e.gl.clear(!0,!0,!1),e.gl.render(e.scene,e.camera),gD.constant=-(f-LE),e.gl.clippingPlanes=_D;let p=e.scene.overrideMaterial,m=e.scene.background;e.scene.overrideMaterial=vD,e.scene.background=null,e.gl.autoClear=!1,e.gl.render(e.scene,e.camera),e.scene.overrideMaterial=p,e.scene.background=m,e.gl.setRenderTarget(c),e.gl.autoClear=l,e.gl.clippingPlanes=u,t.visible=d,i.uDepthTexture&&i.uSceneColor&&i.uCameraNear&&i.uCameraFar&&i.uUseSceneDepth&&(i.uDepthTexture.value=this.scenePassTarget.depthTexture,i.uSceneColor.value=this.scenePassTarget.texture,i.uCameraNear.value=e.camera.near,i.uCameraFar.value=e.camera.far,i.uUseSceneDepth.value=1,i.uUseRefraction&&(i.uUseRefraction.value=+!!this.refraction),i.uEnableFoam&&(i.uEnableFoam.value=+!!this.foam))}underwaterAt(e,t,n){if(this.underwater===!1)return null;let r=rD(this,this._scratchA);if(!aE(e,t,n,{centerX:r.x,centerY:r.y,centerZ:r.z,halfW:(this.size[0]??1)/2,halfD:(this.size[1]??1)/2},pD))return null;let i=cE(this.underwater,this.color);return i.enabled?{...i,surfaceY:r.y}:null}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),this.cubeTarget?.dispose(),this.cubeTarget=null,this.cubeCamera=null,this.scenePassTarget?.depthTexture?.dispose(),this.scenePassTarget?.dispose(),this.scenePassTarget=null,super.free()}rebuildSurfaceIfNeeded(e){let t=JSON.stringify([this.size,this.quality]);if(t===this.surfaceKey&&e.geometry.getAttribute(`position`))return;this.surfaceKey=t,e.geometry?.dispose(),e.material?.dispose?.();let n=this.size[0]??1,r=this.size[1]??1;this.quality===`simple`?(e.geometry=oD(n,r,VE),e.material=this.buildLakeMaterial()):(e.geometry=oD(n,r,Math.min(Math.max(Math.round(Math.max(n,r)*RE),zE),BE)),e.material=this.buildFancyMaterial())}buildFancyMaterial(){return new tc({vertexShader:rE,fragmentShader:iE,fog:!0,uniforms:{fogColor:{value:new W(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.opacity},uEnvironmentMap:{value:null},uUseEnvironmentMap:{value:0},uWavesAmplitude:{value:this.waveHeight*PE},uWavesSpeed:{value:pE.speed},uWavesFrequency:{value:pE.frequency},uWavesPersistence:{value:pE.persistence},uWavesLacunarity:{value:pE.lacunarity},uWavesIterations:{value:pE.iterations},uTroughColor:{value:new W(kE.trough)},uSurfaceColor:{value:new W(kE.surface)},uPeakColor:{value:new W(kE.peak)},uPeakThreshold:{value:AE.peakThreshold},uPeakTransition:{value:AE.peakTransition},uTroughThreshold:{value:AE.troughThreshold},uTroughTransition:{value:AE.troughTransition},uFresnelScale:{value:AE.fresnelScale},uFresnelPower:{value:AE.fresnelPower},uScale:{value:new V(1,1,1)},uWaterCenter:{value:new V},uRipples:{value:Array.from({length:8},()=>new xi)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uSunDirection:{value:new V(.5,.8,.3)},uSunColor:{value:new W(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uDetailStrength:{value:this.detailStrength},uAbsorption:{value:this.absorption},uUseSceneDepth:{value:0},uUseRefraction:{value:0},uSceneColor:{value:null},uEnableFoam:{value:0},uFoamColor:{value:new W(jE.color)},uFoamIntensity:{value:jE.intensity},uFoamRange:{value:ME(this.size[0]??1,this.size[1]??1)},uFoamScale:{value:jE.scale},uDepthTexture:{value:null},uCameraNear:{value:.1},uCameraFar:{value:1e3},uEdgeColor:{value:new W(jE.edgeColor)},uEdgeIntensity:{value:jE.edgeIntensity},uEdgeWidth:{value:jE.edgeWidth}},transparent:!0,depthTest:!0,depthWrite:!0,side:2})}buildLakeMaterial(){return new tc({vertexShader:tE,fragmentShader:nE,fog:!0,uniforms:{fogColor:{value:new W(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.opacity},uColor:{value:new W(this.color)},uSurfaceColor:{value:new W(this.color)},uSkyColor:{value:new W(this.color)},uSunDirection:{value:new V(.5,.8,.3).normalize()},uSunColor:{value:new W(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uDetailStrength:{value:this.detailStrength},uFresnelPower:{value:AE.fresnelPower},uScale:{value:new V(1,1,1)},uWaterCenter:{value:new V},uRipples:{value:Array.from({length:8},()=>new xi)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uFoamColor:{value:new W(jE.color)}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}syncFancy(e){let t=e.material.uniforms,n=this.size[0]??1,r=this.size[1]??1,i=rD(this);t.uTime&&(t.uTime.value=this.time),t.uOpacity&&(t.uOpacity.value=this.opacity),t.uWavesAmplitude&&(t.uWavesAmplitude.value=this.waveHeight*PE),(t.uScale?.value)?.set(n/2,r/2,r/2),(t.uWaterCenter?.value)?.set(i.x,i.y,i.z);let a=this.resolvePalette();(t.uTroughColor?.value)?.copy(a.trough),(t.uSurfaceColor?.value)?.copy(a.surface),(t.uPeakColor?.value)?.copy(a.peak),(t.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(t.uSunColor?.value)?.set(this.sunColor),t.uSunIntensity&&(t.uSunIntensity.value=this.sunIntensity),t.uDetailStrength&&(t.uDetailStrength.value=this.detailStrength),t.uAbsorption&&(t.uAbsorption.value=this.absorption),!this.reflection&&t.uUseEnvironmentMap&&(t.uUseEnvironmentMap.value=0),!this.foam&&t.uEnableFoam&&(t.uEnableFoam.value=0),!this.refraction&&t.uUseRefraction&&(t.uUseRefraction.value=0),t.uSplashFoam&&(t.uSplashFoam.value=+!!this.splash);let o=t.uRipples?.value,s=t.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}}_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])}resolvePalette(){let t=this.colors,n=this.color===e.props.color?.default?null:this.color,r=t.surface??n??kE.surface;return uD.surface.set(r),t.trough?uD.trough.set(t.trough):n?uD.trough.set(n).lerp(sD,.45):uD.trough.set(kE.trough),t.peak?uD.peak.set(t.peak):n?uD.peak.set(n).lerp(cD,.3):uD.peak.set(kE.peak),uD}syncSimple(e){let t=e.material;t.opacity=this.opacity;let n=t.uniforms,r=this.size[0]??1,i=this.size[1]??1,a=rD(this,this._scratchA);n.uTime&&(n.uTime.value=this.time),n.uOpacity&&(n.uOpacity.value=this.opacity),(n.uSurfaceColor?.value)?.set(this.color).lerp(cD,.12),(n.uColor?.value)?.set(this.color).lerp(sD,.4),(n.uSkyColor?.value)?.set(this.color).lerp(lD,.82),(n.uScale?.value)?.set(r/2,i/2,i/2),(n.uWaterCenter?.value)?.set(a.x,a.y,a.z),(n.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(n.uSunColor?.value)?.set(this.sunColor),n.uSunIntensity&&(n.uSunIntensity.value=this.sunIntensity),n.uDetailStrength&&(n.uDetailStrength.value=this.detailStrength),n.uSplashFoam&&(n.uSplashFoam.value=+!!this.splash);let o=n.uRipples?.value,s=n.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}let c=e.geometry,l=c.getAttribute(`position`),u=c.getAttribute(`normal`),d=this.time,f=this.waveHeight,p=a.x,m=a.z,h=this._ripples,g=.5;for(let e=0;e<l.count;e++){let t=l.getX(e),n=l.getZ(e),r=EE(t,n,d,f)+$T(t+p,n+m,h);l.setY(e,r);let i=EE(t+g,n,d,f)+$T(t+p+g,n+m,h),a=EE(t,n+g,d,f)+$T(t+p,n+m+g,h),o=(r-i)/g,s=(r-a)/g,c=1/Math.hypot(o,1,s);u.setXYZ(e,o*c,c,s*c)}l.needsUpdate=!0,u.needsUpdate=!0}stepInteraction(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;n.length=0,nD(t,n);let r=rD(this,this._scratchA),i=(this.size[0]??0)/2,a=(this.size[1]??0)/2,o=[];for(let e of n){let t=rD(e,this._scratchB);if(Math.abs(t.x-r.x)>i||Math.abs(t.z-r.z)>a)continue;let n=qT(e.collider);o.push({id:e,x:t.x,y:t.y,z:t.z,waterline:r.y+this.waveOffsetAt(t.x,t.z,r)+n})}let{entered:s,exited:c,inWater:l}=YT(this.inWater,o,HE);this.inWater=l;let u=this.splash;for(let e of s){let t=Math.abs(iD(e.id)?.[1]??0);XT(this._ripples,e.x,e.z,aD(e.id),u?JT(t):0),this.emit(`entered`,e.id)}for(let e of c)XT(this._ripples,e.x,e.z,KE,u?ZE:0),this.emit(`exited`,e.id);for(let t of eE(this.bobTimers,l,e,qE)){let e=rD(t,this._scratchB);XT(this._ripples,e.x,e.z,JE)}for(let e of l){let t=rD(e,this._scratchB),n=this.wadeAnchors.get(e);if(!n){this.wadeAnchors.set(e,{x:t.x,z:t.z});continue}let r=t.x-n.x,i=t.z-n.z;if(r*r+i*i>=YE*YE){let r=iD(e),i=Math.hypot(r?.[0]??0,r?.[2]??0),a=u?Math.min(QE+$E*i,eD):0;XT(this._ripples,t.x,t.z,XE,a),n.x=t.x,n.z=t.z}}for(let e of this.wadeAnchors.keys())l.has(e)||this.wadeAnchors.delete(e)}waveOffsetAt(e,t,n){return this.quality===`simple`?EE(e-n.x,t-n.z,this.time,this.waveHeight):TE(e,t,this.time,{amplitude:this.waveHeight*PE,frequency:pE.frequency,persistence:pE.persistence,lacunarity:pE.lacunarity,iterations:pE.iterations,speed:pE.speed,scaleNorm:NE})}};function nD(e,t){(e instanceof My||e instanceof jy)&&t.push(e);for(let n of e.children)nD(n,t)}function rD(e,t={x:0,y:0,z:0}){let n=0,r=0,i=0,a=e;for(;a;)a instanceof Dy&&(n+=a.position[0]??0,r+=a.position[1]??0,i+=a.position[2]??0),a=a.parent;return t.x=n,t.y=r,t.z=i,t}function iD(e){return e.velocity??e.linearVelocity}function aD(e){let t=Math.abs(iD(e)?.[1]??0);return Math.min(UE+WE*t,GE)}function oD(e,t,n){let r=new Gs(e,t,n,n);return r.rotateX(-Math.PI/2),r}var sD=new W(`#000000`),cD=new W(`#ffffff`),lD=new W(`#cfe3f0`),uD={trough:new W,surface:new W,peak:new W},dD=new z,fD=new V,pD=3,mD=new cs(new V(0,-1,0),0),hD=[mD],gD=new cs(new V(0,1,0),0),_D=[gD],vD=new ac;vD.colorWrite=!1;function yD(){lt(),j(Dy),j(nw),j(BC),j(WC),j(Bb),j(Vb),j(Jb),j(mx),j(zT),j(Ny),j(lw),j(fb),j(tD),j(wC),j(dS),j(yT),j($C),j(Yb),j(LC),j(RC),j(ky),j(jy),j(Ay),j(My)}var bD=`
6874
+ `;function pE(e,t,n,r,i=0){return t>=r.centerY?!1:Math.abs(e-r.centerX)<=r.halfW+i&&Math.abs(n-r.centerZ)<=r.halfD+i}var mE=22,hE={enabled:!0,color:`#cdeeff`,intensity:.55,scale:.32,speed:1};function gE(e,t){if(e===!1)return{enabled:!1,color:vE(t),visibility:mE,caustics:hE};let n=e&&typeof e==`object`?e:{};return{enabled:!0,color:n.color??vE(t),visibility:n.visibility??mE,caustics:_E(n.caustics)}}function _E(e){if(e===!1)return{...hE,enabled:!1};let t=e&&typeof e==`object`?e:{};return{enabled:!0,color:typeof t.color==`string`?t.color:hE.color,intensity:typeof t.intensity==`number`?t.intensity:hE.intensity,scale:typeof t.scale==`number`?t.scale:hE.scale,speed:typeof t.speed==`number`?t.speed:hE.speed}}function vE(e){let{r:t,g:n,b:r}=yE(e),i=(e,t,n)=>Math.round(e*(1-n)+t*n);return bE(Math.round(i(t,6,.45)*.7),Math.round(i(n,40,.4)*.78),Math.round(i(r,70,.35)*.82))}function yE(e){let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return{r:Number.parseInt(n.slice(0,2),16)||0,g:Number.parseInt(n.slice(2,4),16)||0,b:Number.parseInt(n.slice(4,6),16)||0}}function bE(e,t,n){let r=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,`0`);return`#${r(e)}${r(t)}${r(n)}`}var xE={frequency:6.7,persistence:.3,lacunarity:2.18,iterations:9,speed:.5},SE=.525,CE=.08,wE={freqX:.7,freqZ:.5,cross:.6};function TE(e,t){return e-Math.floor(e/t)*t}function EE(e){return e-Math.floor(e)}function DE(e){return TE((e*34+1)*e,289)}var OE=.211324865405187,kE=.366025403784439,AE=-.577350269189626,jE=.024390243902439;function ME(e,t){let n=Math.floor(e+(e+t)*kE),r=Math.floor(t+(e+t)*kE),i=e-n+(n+r)*OE,a=t-r+(n+r)*OE,o=+(i>a),s=i>a?0:1,c=i+OE-o,l=a+OE-s,u=i+AE,d=a+AE;n=TE(n,289),r=TE(r,289);let f=DE(DE(r)+n),p=DE(DE(r+s)+n+o),m=DE(DE(r+1)+n+1),h=Math.max(.5-(i*i+a*a),0),g=Math.max(.5-(c*c+l*l),0),_=Math.max(.5-(u*u+d*d),0);h*=h,h*=h,g*=g,g*=g,_*=_,_*=_;let v=2*EE(f*jE)-1,y=2*EE(p*jE)-1,b=2*EE(m*jE)-1,x=Math.abs(v)-.5,S=Math.abs(y)-.5,C=Math.abs(b)-.5,w=v-Math.floor(v+.5),T=y-Math.floor(y+.5),E=b-Math.floor(b+.5);h*=1.79284291400159-.85373472095314*(w*w+x*x),g*=1.79284291400159-.85373472095314*(T*T+S*S),_*=1.79284291400159-.85373472095314*(E*E+C*C);let D=w*i+x*a,O=T*c+S*l,k=E*u+C*d;return 130*(h*D+g*O+_*k)}function NE(e,t,n,r){let i=Math.max(r.scaleNorm,1e-6),a=e/i,o=t/i,s=0,c=1,l=r.frequency,u=n*r.speed;for(let e=0;e<r.iterations;e++)s+=c*ME(a*l+u,o*l+u),c*=r.persistence,l*=r.lacunarity;return s*r.amplitude}function PE(e,t,n,r){return r*(Math.sin(e*wE.freqX+n)+wE.cross*Math.sin(t*wE.freqZ+n*1.3))}var FE=[`fancy`,`simple`],IE=[`trough`,`surface`,`peak`],LE={trough:`#135a72`,surface:`#2a86a0`,peak:`#a5ddd6`},RE={peakThreshold:.08,peakTransition:.05,troughThreshold:-.01,troughTransition:.15,fresnelScale:1,fresnelPower:5},zE={color:`#dcebe8`,intensity:.32,rangeMin:.45,rangeMax:1.4,scale:.35,edgeColor:`#ffffff`,edgeIntensity:.6,edgeWidth:.5};function BE(e,t){return Math.min(zE.rangeMax,Math.max(zE.rangeMin,Math.min(e,t)*.012))}var VE=128,HE=SE/CE,UE=256,WE=1024,GE=.02,KE=4,qE=32,JE=256,YE=32,XE=.05,ZE=.08,QE=.02,$E=.18,eD=.04,tD=1.4,nD=.04,rD=.45,iD=.08,aD=.4,oD=.22,sD=.09,cD=.85,lD=class e extends Dy{static typeName=`Water3D`;static signals=[`entered`,`exited`];static props={size:{default:[40,40]},color:{default:`#2a6fbe`},opacity:{default:.8},renderOrder:{default:1},waveHeight:{default:.04},waveSpeed:{default:1},quality:{default:`fancy`,options:FE},colors:{default:{}},reflection:{default:!0},reflectionInterval:{default:1e3},foam:{default:!0},interaction:{default:!0},splash:{default:!0},sunDirection:{default:[.5,.8,.3]},sunColor:{default:`#fff5d6`},sunIntensity:{default:1},detailStrength:{default:.26},absorption:{default:.15},refraction:{default:!0},underwater:{default:!0}};size=[40,40];color=`#2a6fbe`;opacity=.8;renderOrder=1;waveHeight=.04;waveSpeed=1;quality=`fancy`;colors={};reflection=!0;reflectionInterval=1e3;foam=!0;interaction=!0;splash=!0;sunDirection=[.5,.8,.3];sunColor=`#fff5d6`;sunIntensity=1;detailStrength=.26;absorption=.15;refraction=!0;underwater=!0;static validateJson(e){let t=e;if(!((t.size[0]??0)>0)||!((t.size[1]??0)>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' size must be positive [width, depth] meters, got ${JSON.stringify(t.size)}.`,{prop:`size`});if(!FE.includes(t.quality))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' quality must be one of [${FE.join(`, `)}], got '${t.quality}'.`,{prop:`quality`,validOptions:FE});for(let[n,r]of Object.entries(t.colors)){if(!IE.includes(n))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' colors has unknown key '${n}'. Valid keys: [${IE.join(`, `)}].`,{prop:`colors`,validOptions:IE});if(typeof r!=`string`)throw new y(`BAD_FORMAT`,`Water3D '${e.name}' colors.${n} must be a hex color string, got ${JSON.stringify(r)}.`,{prop:`colors`})}if(!(t.reflectionInterval>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' reflectionInterval must be > 0 ms, got ${t.reflectionInterval}.`,{prop:`reflectionInterval`});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 y(`BAD_FORMAT`,`Water3D '${e.name}' sunDirection must be a non-zero [x, y, z] vector, got ${JSON.stringify(n)}.`,{prop:`sunDirection`});if(!(t.sunIntensity>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' sunIntensity must be >= 0, got ${t.sunIntensity}.`,{prop:`sunIntensity`});if(!(t.detailStrength>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' detailStrength must be >= 0, got ${t.detailStrength}.`,{prop:`detailStrength`});if(!(t.absorption>=0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' absorption must be >= 0 (per-meter Beer's-law constant), got ${t.absorption}.`,{prop:`absorption`});let r=t.underwater;if(typeof r!=`boolean`){if(typeof r!=`object`||!r||Array.isArray(r))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater must be true, false or an object ({ color?, visibility? }), got ${JSON.stringify(r)}.`,{prop:`underwater`});let t=r;if(t.color!==void 0&&typeof t.color!=`string`)throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater.color must be a hex color string, got ${JSON.stringify(t.color)}.`,{prop:`underwater`});if(t.visibility!==void 0&&!(t.visibility>0))throw new y(`BAD_FORMAT`,`Water3D '${e.name}' underwater.visibility must be > 0 meters, got ${JSON.stringify(t.visibility)}.`,{prop:`underwater`})}}time=0;surfaceKey=``;_ripples=[];inWater=new Set;bobTimers=new Map;wadeAnchors=new Map;_scratchA={x:0,y:0,z:0};_scratchB={x:0,y:0,z:0};_bodies=[];cubeTarget=null;cubeCamera=null;reflectionNear=0;lastReflectionAt=0;scenePassTarget=null;_createObject3D(){return new Mo}update(e){this.time+=e*this.waveSpeed,aE(this._ripples,e),this.interaction&&this.stepInteraction(e)}_syncObject3D(){super._syncObject3D();let e=this._ensureObject3D();this.rebuildSurfaceIfNeeded(e),this.quality===`simple`?this.syncSimple(e):this.syncFancy(e)}_onRender3D(e){let t=this._ensureObject3D(),n=t.material;if(e.camera.updateWorldMatrix(!0,!1),e.camera.getWorldPosition(bD),this.underwaterAt(bD.x,bD.y,bD.z)||this.quality!==`fancy`||!n.isShaderMaterial)return;let r=Math.hypot((this.size[0]??1)/2,(this.size[1]??1)/2);if(!eE(e.camera,dD(this),r+1))return;let i=n.uniforms,a=Date.now();if(this.reflection){this.cubeTarget||=new pu(UE,{generateMipmaps:!0,minFilter:Gt,type:$t});let n=Math.max((this.size[0]??1)/2,(this.size[1]??1)/2);if((!this.cubeCamera||this.reflectionNear!==n)&&(this.reflectionNear=n,this.cubeCamera=new ul(n,1e3,this.cubeTarget),this.lastReflectionAt=0),this.lastReflectionAt===0||a-this.lastReflectionAt>=this.reflectionInterval){this.lastReflectionAt=a;let n=dD(this),r=this.cubeCamera;r.position.set(n.x,n.y+.1,n.z);let i=t.visible;t.visible=!1,r.update(e.gl,e.scene),t.visible=i}i.uEnvironmentMap&&i.uUseEnvironmentMap&&(i.uEnvironmentMap.value=this.cubeTarget.texture,i.uUseEnvironmentMap.value=1)}e.gl.getDrawingBufferSize(yD);let o=Math.max(1,Math.min(Math.round(yD.x/2),WE)),s=Math.max(1,Math.min(Math.round(yD.y/2),WE));if(this.scenePassTarget&&(this.scenePassTarget.width!==o||this.scenePassTarget.height!==s)&&(this.scenePassTarget.depthTexture?.dispose(),this.scenePassTarget.dispose(),this.scenePassTarget=null),!this.scenePassTarget){let e=new Is(o,s);e.type=Qt,this.scenePassTarget=new Ci(o,s,{depthTexture:e,depthBuffer:!0,stencilBuffer:!1,generateMipmaps:!0,minFilter:Gt})}let c=e.gl.getRenderTarget(),l=e.gl.autoClear,u=e.gl.clippingPlanes,d=t.visible;t.visible=!1;let f=dD(this).y;SD.constant=f+GE,e.gl.clippingPlanes=CD,e.gl.setRenderTarget(this.scenePassTarget),e.gl.autoClear=!0,e.gl.clear(!0,!0,!1),e.gl.render(e.scene,e.camera),wD.constant=-(f-GE),e.gl.clippingPlanes=TD;let p=e.scene.overrideMaterial,m=e.scene.background;e.scene.overrideMaterial=ED,e.scene.background=null,e.gl.autoClear=!1,e.gl.render(e.scene,e.camera),e.scene.overrideMaterial=p,e.scene.background=m,e.gl.setRenderTarget(c),e.gl.autoClear=l,e.gl.clippingPlanes=u,t.visible=d,i.uDepthTexture&&i.uSceneColor&&i.uCameraNear&&i.uCameraFar&&i.uUseSceneDepth&&(i.uDepthTexture.value=this.scenePassTarget.depthTexture,i.uSceneColor.value=this.scenePassTarget.texture,i.uCameraNear.value=e.camera.near,i.uCameraFar.value=e.camera.far,i.uUseSceneDepth.value=1,i.uUseRefraction&&(i.uUseRefraction.value=+!!this.refraction),i.uEnableFoam&&(i.uEnableFoam.value=+!!this.foam))}underwaterAt(e,t,n){if(this.underwater===!1)return null;let r=dD(this,this._scratchA);if(!pE(e,t,n,{centerX:r.x,centerY:r.y,centerZ:r.z,halfW:(this.size[0]??1)/2,halfD:(this.size[1]??1)/2},xD))return null;let i=gE(this.underwater,this.color);return i.enabled?{...i,surfaceY:r.y}:null}free(){let e=this._ensureObject3D();e.geometry?.dispose(),e.material?.dispose?.(),this.cubeTarget?.dispose(),this.cubeTarget=null,this.cubeCamera=null,this.scenePassTarget?.depthTexture?.dispose(),this.scenePassTarget?.dispose(),this.scenePassTarget=null,super.free()}rebuildSurfaceIfNeeded(e){let t=JSON.stringify([this.size,this.quality]);if(t===this.surfaceKey&&e.geometry.getAttribute(`position`))return;this.surfaceKey=t,e.geometry?.dispose(),e.material?.dispose?.();let n=this.size[0]??1,r=this.size[1]??1;this.quality===`simple`?(e.geometry=mD(n,r,YE),e.material=this.buildLakeMaterial()):(e.geometry=mD(n,r,Math.min(Math.max(Math.round(Math.max(n,r)*KE),qE),JE)),e.material=this.buildFancyMaterial())}buildFancyMaterial(){return new tc({vertexShader:dE,fragmentShader:fE,fog:!0,uniforms:{fogColor:{value:new W(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.opacity},uEnvironmentMap:{value:null},uUseEnvironmentMap:{value:0},uWavesAmplitude:{value:this.waveHeight*HE},uWavesSpeed:{value:xE.speed},uWavesFrequency:{value:xE.frequency},uWavesPersistence:{value:xE.persistence},uWavesLacunarity:{value:xE.lacunarity},uWavesIterations:{value:xE.iterations},uTroughColor:{value:new W(LE.trough)},uSurfaceColor:{value:new W(LE.surface)},uPeakColor:{value:new W(LE.peak)},uPeakThreshold:{value:RE.peakThreshold},uPeakTransition:{value:RE.peakTransition},uTroughThreshold:{value:RE.troughThreshold},uTroughTransition:{value:RE.troughTransition},uFresnelScale:{value:RE.fresnelScale},uFresnelPower:{value:RE.fresnelPower},uScale:{value:new V(1,1,1)},uWaterCenter:{value:new V},uRipples:{value:Array.from({length:8},()=>new xi)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uSunDirection:{value:new V(.5,.8,.3)},uSunColor:{value:new W(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uDetailStrength:{value:this.detailStrength},uAbsorption:{value:this.absorption},uUseSceneDepth:{value:0},uUseRefraction:{value:0},uSceneColor:{value:null},uEnableFoam:{value:0},uFoamColor:{value:new W(zE.color)},uFoamIntensity:{value:zE.intensity},uFoamRange:{value:BE(this.size[0]??1,this.size[1]??1)},uFoamScale:{value:zE.scale},uDepthTexture:{value:null},uCameraNear:{value:.1},uCameraFar:{value:1e3},uEdgeColor:{value:new W(zE.edgeColor)},uEdgeIntensity:{value:zE.edgeIntensity},uEdgeWidth:{value:zE.edgeWidth}},transparent:!0,depthTest:!0,depthWrite:!0,side:2})}buildLakeMaterial(){return new tc({vertexShader:lE,fragmentShader:uE,fog:!0,uniforms:{fogColor:{value:new W(`#ffffff`)},fogNear:{value:1},fogFar:{value:1e3},fogDensity:{value:25e-5},uTime:{value:0},uOpacity:{value:this.opacity},uColor:{value:new W(this.color)},uSurfaceColor:{value:new W(this.color)},uSkyColor:{value:new W(this.color)},uSunDirection:{value:new V(.5,.8,.3).normalize()},uSunColor:{value:new W(this.sunColor)},uSunIntensity:{value:this.sunIntensity},uDetailStrength:{value:this.detailStrength},uFresnelPower:{value:RE.fresnelPower},uScale:{value:new V(1,1,1)},uWaterCenter:{value:new V},uRipples:{value:Array.from({length:8},()=>new xi)},uRippleFoam:{value:Array.from({length:8},()=>0)},uSplashFoam:{value:+!!this.splash},uFoamColor:{value:new W(zE.color)}},transparent:!0,depthTest:!0,depthWrite:!1,side:2})}syncFancy(e){let t=e.material.uniforms,n=this.size[0]??1,r=this.size[1]??1,i=dD(this);t.uTime&&(t.uTime.value=this.time),t.uOpacity&&(t.uOpacity.value=this.opacity),t.uWavesAmplitude&&(t.uWavesAmplitude.value=this.waveHeight*HE),(t.uScale?.value)?.set(n/2,r/2,r/2),(t.uWaterCenter?.value)?.set(i.x,i.y,i.z);let a=this.resolvePalette();(t.uTroughColor?.value)?.copy(a.trough),(t.uSurfaceColor?.value)?.copy(a.surface),(t.uPeakColor?.value)?.copy(a.peak),(t.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(t.uSunColor?.value)?.set(this.sunColor),t.uSunIntensity&&(t.uSunIntensity.value=this.sunIntensity),t.uDetailStrength&&(t.uDetailStrength.value=this.detailStrength),t.uAbsorption&&(t.uAbsorption.value=this.absorption),!this.reflection&&t.uUseEnvironmentMap&&(t.uUseEnvironmentMap.value=0),!this.foam&&t.uEnableFoam&&(t.uEnableFoam.value=0),!this.refraction&&t.uUseRefraction&&(t.uUseRefraction.value=0),t.uSplashFoam&&(t.uSplashFoam.value=+!!this.splash);let o=t.uRipples?.value,s=t.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}}_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])}resolvePalette(){let t=this.colors,n=this.color===e.props.color?.default?null:this.color,r=t.surface??n??LE.surface;return vD.surface.set(r),t.trough?vD.trough.set(t.trough):n?vD.trough.set(n).lerp(hD,.45):vD.trough.set(LE.trough),t.peak?vD.peak.set(t.peak):n?vD.peak.set(n).lerp(gD,.3):vD.peak.set(LE.peak),vD}syncSimple(e){let t=e.material;t.opacity=this.opacity;let n=t.uniforms,r=this.size[0]??1,i=this.size[1]??1,a=dD(this,this._scratchA);n.uTime&&(n.uTime.value=this.time),n.uOpacity&&(n.uOpacity.value=this.opacity),(n.uSurfaceColor?.value)?.set(this.color).lerp(gD,.12),(n.uColor?.value)?.set(this.color).lerp(hD,.4),(n.uSkyColor?.value)?.set(this.color).lerp(_D,.82),(n.uScale?.value)?.set(r/2,i/2,i/2),(n.uWaterCenter?.value)?.set(a.x,a.y,a.z),(n.uSunDirection?.value)?.set(this.sunDirection[0]??0,this.sunDirection[1]??1,this.sunDirection[2]??0).normalize(),(n.uSunColor?.value)?.set(this.sunColor),n.uSunIntensity&&(n.uSunIntensity.value=this.sunIntensity),n.uDetailStrength&&(n.uDetailStrength.value=this.detailStrength),n.uSplashFoam&&(n.uSplashFoam.value=+!!this.splash);let o=n.uRipples?.value,s=n.uRippleFoam?.value;if(o)for(let e=0;e<o.length;e++){let t=this._ripples[e];t?o[e].set(t.x,t.z,t.age,t.amp):o[e].set(0,0,0,0),s&&(s[e]=t?t.foam??0:0)}let c=e.geometry,l=c.getAttribute(`position`),u=c.getAttribute(`normal`),d=this.time,f=this.waveHeight,p=a.x,m=a.z,h=this._ripples,g=.5;for(let e=0;e<l.count;e++){let t=l.getX(e),n=l.getZ(e),r=PE(t,n,d,f)+sE(t+p,n+m,h);l.setY(e,r);let i=PE(t+g,n,d,f)+sE(t+p+g,n+m,h),a=PE(t,n+g,d,f)+sE(t+p,n+m+g,h),o=(r-i)/g,s=(r-a)/g,c=1/Math.hypot(o,1,s);u.setXYZ(e,o*c,c,s*c)}l.needsUpdate=!0,u.needsUpdate=!0}stepInteraction(e){let t=this;for(;t.parent;)t=t.parent;let n=this._bodies;n.length=0,uD(t,n);let r=dD(this,this._scratchA),i=(this.size[0]??0)/2,a=(this.size[1]??0)/2,o=[];for(let e of n){let t=dD(e,this._scratchB);if(Math.abs(t.x-r.x)>i||Math.abs(t.z-r.z)>a)continue;let n=tE(e.collider);o.push({id:e,x:t.x,y:t.y,z:t.z,waterline:r.y+this.waveOffsetAt(t.x,t.z,r)+n})}let{entered:s,exited:c,inWater:l}=rE(this.inWater,o,XE);this.inWater=l;let u=this.splash;for(let e of s){let t=Math.abs(fD(e.id)?.[1]??0);iE(this._ripples,e.x,e.z,pD(e.id),u?nE(t):0),this.emit(`entered`,e.id)}for(let e of c)iE(this._ripples,e.x,e.z,eD,u?aD:0),this.emit(`exited`,e.id);for(let t of cE(this.bobTimers,l,e,tD)){let e=dD(t,this._scratchB);iE(this._ripples,e.x,e.z,nD)}for(let e of l){let t=dD(e,this._scratchB),n=this.wadeAnchors.get(e);if(!n){this.wadeAnchors.set(e,{x:t.x,z:t.z});continue}let r=t.x-n.x,i=t.z-n.z;if(r*r+i*i>=rD*rD){let r=fD(e),i=Math.hypot(r?.[0]??0,r?.[2]??0),a=u?Math.min(oD+sD*i,cD):0;iE(this._ripples,t.x,t.z,iD,a),n.x=t.x,n.z=t.z}}for(let e of this.wadeAnchors.keys())l.has(e)||this.wadeAnchors.delete(e)}waveOffsetAt(e,t,n){return this.quality===`simple`?PE(e-n.x,t-n.z,this.time,this.waveHeight):NE(e,t,this.time,{amplitude:this.waveHeight*HE,frequency:xE.frequency,persistence:xE.persistence,lacunarity:xE.lacunarity,iterations:xE.iterations,speed:xE.speed,scaleNorm:VE})}};function uD(e,t){(e instanceof My||e instanceof jy)&&t.push(e);for(let n of e.children)uD(n,t)}function dD(e,t={x:0,y:0,z:0}){let n=0,r=0,i=0,a=e;for(;a;)a instanceof Dy&&(n+=a.position[0]??0,r+=a.position[1]??0,i+=a.position[2]??0),a=a.parent;return t.x=n,t.y=r,t.z=i,t}function fD(e){return e.velocity??e.linearVelocity}function pD(e){let t=Math.abs(fD(e)?.[1]??0);return Math.min(ZE+QE*t,$E)}function mD(e,t,n){let r=new Gs(e,t,n,n);return r.rotateX(-Math.PI/2),r}var hD=new W(`#000000`),gD=new W(`#ffffff`),_D=new W(`#cfe3f0`),vD={trough:new W,surface:new W,peak:new W},yD=new z,bD=new V,xD=3,SD=new cs(new V(0,-1,0),0),CD=[SD],wD=new cs(new V(0,1,0),0),TD=[wD],ED=new ac;ED.colorWrite=!1;function DD(){lt(),M(Dy),M(uw),M(JC),M(QC),M(Bb),M(Vb),M(Jb),M(Sx),M(qT),M(Ny),M(_w),M(Yb),M(fb),M(lD),M(MC),M(yS),M(DT),M(sw),M(nx),M(GC),M(KC),M(ky),M(jy),M(Ay),M(My)}var OD=`
6875
6875
  varying vec2 vUv;
6876
6876
  void main() {
6877
6877
  vUv = uv;
6878
6878
  gl_Position = vec4(position.xy, 0.0, 1.0);
6879
6879
  }
6880
- `,xD=`
6880
+ `,kD=`
6881
6881
  precision highp float;
6882
6882
  varying vec2 vUv;
6883
6883
  uniform sampler2D tScene;
@@ -6891,7 +6891,7 @@ void main() {
6891
6891
  float k = max(l - uThreshold, 0.0);
6892
6892
  gl_FragColor = vec4(c * (k / max(l, 1e-4)), 1.0);
6893
6893
  }
6894
- `,SD=`
6894
+ `,AD=`
6895
6895
  precision highp float;
6896
6896
  varying vec2 vUv;
6897
6897
  uniform sampler2D tTex;
@@ -6905,7 +6905,7 @@ void main() {
6905
6905
  sum += texture2D(tTex, vUv - uDir * 3.2308) * 0.0702703;
6906
6906
  gl_FragColor = sum;
6907
6907
  }
6908
- `,CD=`
6908
+ `,jD=`
6909
6909
  precision highp float;
6910
6910
  varying vec2 vUv;
6911
6911
  uniform sampler2D tScene;
@@ -6923,13 +6923,13 @@ void main() {
6923
6923
  #include <tonemapping_fragment>
6924
6924
  #include <colorspace_fragment>
6925
6925
  }
6926
- `;function wD(e,t){let n=new tc({vertexShader:bD,fragmentShader:e,depthTest:!1,depthWrite:!1,uniforms:t}),r=new Mo(new Gs(2,2),n);return r.frustumCulled=!1,r}function TD(){let e=wD(xD,{tScene:{value:null},uThreshold:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}function ED(){let e=wD(SD,{tTex:{value:null},uDir:{value:new z}});return{mesh:e,uniforms:e.material.uniforms}}function DD(){let e=wD(CD,{tScene:{value:null},tBloom:{value:null},uStrength:{value:.85}});return{mesh:e,uniforms:e.material.uniforms}}var OD=`
6926
+ `;function MD(e,t){let n=new tc({vertexShader:OD,fragmentShader:e,depthTest:!1,depthWrite:!1,uniforms:t}),r=new Mo(new Gs(2,2),n);return r.frustumCulled=!1,r}function ND(){let e=MD(kD,{tScene:{value:null},uThreshold:{value:1}});return{mesh:e,uniforms:e.material.uniforms}}function PD(){let e=MD(AD,{tTex:{value:null},uDir:{value:new z}});return{mesh:e,uniforms:e.material.uniforms}}function FD(){let e=MD(jD,{tScene:{value:null},tBloom:{value:null},uStrength:{value:.85}});return{mesh:e,uniforms:e.material.uniforms}}var ID=`
6927
6927
  varying vec2 vUv;
6928
6928
  void main() {
6929
6929
  vUv = uv;
6930
6930
  gl_Position = vec4(position.xy, 0.0, 1.0);
6931
6931
  }
6932
- `,kD=`
6932
+ `,LD=`
6933
6933
  precision highp float;
6934
6934
  varying vec2 vUv;
6935
6935
  uniform sampler2D tDepth;
@@ -7091,7 +7091,7 @@ void main() {
7091
7091
  // a separate full-res pass (this raymarch runs at HALF res for performance)
7092
7092
  gl_FragColor = vec4(accum, alpha);
7093
7093
  }
7094
- `,AD=`
7094
+ `,RD=`
7095
7095
  precision highp float;
7096
7096
  varying vec2 vUv;
7097
7097
  uniform sampler2D tTex;
@@ -7109,7 +7109,7 @@ void main() {
7109
7109
  c += texture2D(tTex, vUv - uDir * 4.0) * 0.015;
7110
7110
  gl_FragColor = c;
7111
7111
  }
7112
- `,jD=`
7112
+ `,zD=`
7113
7113
  precision highp float;
7114
7114
  varying vec2 vUv;
7115
7115
  uniform sampler2D tScene;
@@ -7119,11 +7119,11 @@ void main() {
7119
7119
  vec4 cloud = texture2D(tClouds, vUv); // already separable-blurred + premultiplied
7120
7120
  gl_FragColor = vec4(scene.rgb * (1.0 - cloud.a) + cloud.rgb, 1.0);
7121
7121
  }
7122
- `;function MD(){let e=new tc({vertexShader:OD,fragmentShader:AD,depthTest:!1,depthWrite:!1,uniforms:{tTex:{value:null},uDir:{value:new z}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function ND(){let e=new tc({vertexShader:OD,fragmentShader:kD,depthTest:!1,depthWrite:!1,uniforms:{tDepth:{value:null},uInvViewProj:{value:new U},uCameraPos:{value:new V},uTime:{value:0},uSunDir:{value:new V(0,1,0)},uSunColor:{value:new W(`#fff3da`)},uCloudColor:{value:new W(`#ffffff`)},uShadeColor:{value:new W(`#9fb0c8`)},uHorizonColor:{value:new W(`#cdd9e6`)},uBase:{value:120},uTop:{value:320},uCoverage:{value:.5},uDensity:{value:1},uScale:{value:240},uWind:{value:new z(1,.3)},uFarFade:{value:6e3}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function PD(){let e=new tc({vertexShader:OD,fragmentShader:jD,depthTest:!1,depthWrite:!1,uniforms:{tScene:{value:null},tClouds:{value:null}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var FD=class extends Ic{constructor(e){super(e),this.type=$t}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(`
7122
+ `;function BD(){let e=new tc({vertexShader:ID,fragmentShader:RD,depthTest:!1,depthWrite:!1,uniforms:{tTex:{value:null},uDir:{value:new z}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function VD(){let e=new tc({vertexShader:ID,fragmentShader:LD,depthTest:!1,depthWrite:!1,uniforms:{tDepth:{value:null},uInvViewProj:{value:new U},uCameraPos:{value:new V},uTime:{value:0},uSunDir:{value:new V(0,1,0)},uSunColor:{value:new W(`#fff3da`)},uCloudColor:{value:new W(`#ffffff`)},uShadeColor:{value:new W(`#9fb0c8`)},uHorizonColor:{value:new W(`#cdd9e6`)},uBase:{value:120},uTop:{value:320},uCoverage:{value:.5},uDensity:{value:1},uScale:{value:240},uWind:{value:new z(1,.3)},uFarFade:{value:6e3}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}function HD(){let e=new tc({vertexShader:ID,fragmentShader:zD,depthTest:!1,depthWrite:!1,uniforms:{tScene:{value:null},tClouds:{value:null}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var UD=class extends Ic{constructor(e){super(e),this.type=$t}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(`
7123
7123
  `))&&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+`
7124
7124
  `;l=n(e),!1!==l;){if(c.string+=l+`
7125
7125
  `,l.charAt(0)===`#`){c.comments+=l+`
7126
- `;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]=Ha.toHalfFloat(Math.min(e[t+0]*i,65504)),n[r+1]=Ha.toHalfFloat(Math.min(e[t+1]*i,65504)),n[r+2]=Ha.toHalfFloat(Math.min(e[t+2]*i,65504)),n[r+3]=Ha.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 Qt: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=Qt;break;case $t: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=$t;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 Qt:case $t:e.colorSpace=pr,e.minFilter=Ut,e.magFilter=Ut,e.generateMipmaps=!1,e.flipY=!0;break}t&&t(e,n)}return super.load(e,i,n,r)}},ID=class extends FD{constructor(e){console.warn(`RGBELoader has been deprecated. Please use HDRLoader instead.`),super(e)}},LD=class e extends Mo{constructor(){let t=e.SkyShader,n=new tc({name:t.name,uniforms:Qs.clone(t.uniforms),vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,side:1,depthWrite:!1});super(new zs(1,1,1),n),this.isSky=!0}};LD.SkyShader={name:`SkyShader`,uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new V},up:{value:new V(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:`
7126
+ `;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]=Ha.toHalfFloat(Math.min(e[t+0]*i,65504)),n[r+1]=Ha.toHalfFloat(Math.min(e[t+1]*i,65504)),n[r+2]=Ha.toHalfFloat(Math.min(e[t+2]*i,65504)),n[r+3]=Ha.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 Qt: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=Qt;break;case $t: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=$t;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 Qt:case $t:e.colorSpace=pr,e.minFilter=Ut,e.magFilter=Ut,e.generateMipmaps=!1,e.flipY=!0;break}t&&t(e,n)}return super.load(e,i,n,r)}},WD=class extends UD{constructor(e){console.warn(`RGBELoader has been deprecated. Please use HDRLoader instead.`),super(e)}},GD=class e extends Mo{constructor(){let t=e.SkyShader,n=new tc({name:t.name,uniforms:Qs.clone(t.uniforms),vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,side:1,depthWrite:!1});super(new zs(1,1,1),n),this.isSky=!0}};GD.SkyShader={name:`SkyShader`,uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new V},up:{value:new V(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:`
7127
7127
  uniform vec3 sunPosition;
7128
7128
  uniform float rayleigh;
7129
7129
  uniform float turbidity;
@@ -7343,13 +7343,13 @@ void main() {
7343
7343
  #include <tonemapping_fragment>
7344
7344
  #include <colorspace_fragment>
7345
7345
 
7346
- }`};var RD=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],zD=[`color`,`near`,`far`],BD=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],VD=[`threshold`,`strength`],HD=[`mapSize`,`radius`,`static`],UD=[1024,2048],WD=2,GD=1,KD=50,qD=800,JD=`#cfd8e0`,YD=Math.PI/180;function XD(e){return{exposure:eO(e?.exposure),sky:tO(e?.sky),fog:nO(e?.fog,e?.sky!==void 0),clouds:rO(e?.clouds),bloom:iO(e?.bloom),shadows:aO(e?.shadows)}}function ZD(e,t){let n=(90-e)*YD,r=t*YD;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function QD(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function $D(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=cO((e.turbidity-WD)/8),a=QD(e),o=cO((18-Math.asin(sO(a[1],-1,1))/YD)/18)*.8,s=e=>Math.round(lO(lO(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 eO(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new y(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function tO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!RD.includes(e))throw new y(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${RD.join(`, `)}].`,{prop:`sky`,validOptions:RD});if(t.type!==void 0&&t.type!==`atmosphere`)throw new y(`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 y(`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 y(`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=oO(t.elevationDeg,32,`sky.elevationDeg`),n=oO(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new y(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=ZD(e,n)}let i=oO(t.turbidity,WD,`sky.turbidity`);if(i<=0)throw new y(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=oO(t.rayleigh,GD,`sky.rayleigh`);if(a<0)throw new y(`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 nO(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!zD.includes(e))throw new y(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${zD.join(`, `)}].`,{prop:`fog`,validOptions:zD});if(n.color!==void 0&&typeof n.color!=`string`)throw new y(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=oO(n.near,KD,`fog.near`),i=oO(n.far,qD,`fog.far`);if(r<0)throw new y(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new y(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:JD),near:r,far:i}}function rO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!BD.includes(e))throw new y(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${BD.join(`, `)}].`,{prop:`clouds`,validOptions:BD});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new y(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=oO(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=oO(t.density,1,`clouds.density`);if(r<0)throw new y(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=oO(t.base,120,`clouds.base`),a=oO(t.top,320,`clouds.top`);if(a<=i)throw new y(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=oO(t.speed,1,`clouds.speed`),s=oO(t.scale,240,`clouds.scale`);if(s<=0)throw new y(`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 iO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!VD.includes(e))throw new y(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${VD.join(`, `)}].`,{prop:`bloom`,validOptions:VD});let n=oO(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new y(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=oO(t.strength,.8,`bloom.strength`);if(r<0)throw new y(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function aO(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 y(`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(!HD.includes(e))throw new y(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${HD.join(`, `)}].`,{prop:`shadows`,validOptions:HD});let n=t.mapSize===void 0?2048:t.mapSize;if(!UD.includes(n))throw new y(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${UD.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:UD.map(String)});let r=oO(t.radius,1,`shadows.radius`);if(r<0)throw new y(`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 y(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function oO(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new y(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function sO(e,t,n){return Math.min(Math.max(e,t),n)}function cO(e){return sO(e,0,1)}function lO(e,t,n){return e+(t-e)*n}var uO=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,dO={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 fO(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=dO[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(dO).join(`, `)}.`);return`${uO}/${t}`}return null}var pO=75,mO=class{scene;ambient=new il(`#ffffff`,0);envKey=null;config=XD(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new sa(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new W;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?QD(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get sceneFog(){return this.scene.fog instanceof sa?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=XD(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)*hO(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new W(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=pO,t.top=pO,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 sa(`#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=fO(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new ID().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 LD,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 iu(t),r=new ca;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?$D(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 hO(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new y(`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 gO=new Ca,_O=new V,vO=.4,yO=new Float32Array(72);function bO(e){if(!(e instanceof Dy))return null;let t=e._ensureObject3D();if(t.updateWorldMatrix(!0,!0),gO.setFromObject(t),gO.getSize(_O),!Number.isFinite(_O.x)||_O.x===0&&_O.y===0&&_O.z===0){let e=new V().setFromMatrixPosition(t.matrixWorld);gO.min.set(e.x-vO,e.y-vO,e.z-vO),gO.max.set(e.x+vO,e.y+vO,e.z+vO)}else gO.expandByScalar(.02);let{min:n,max:r}=gO,i=0,a=(e,t,n,r,a,o)=>{yO[i++]=e,yO[i++]=t,yO[i++]=n,yO[i++]=r,yO[i++]=a,yO[i++]=o};return a(n.x,n.y,n.z,r.x,n.y,n.z),a(r.x,n.y,n.z,r.x,n.y,r.z),a(r.x,n.y,r.z,n.x,n.y,r.z),a(n.x,n.y,r.z,n.x,n.y,n.z),a(n.x,r.y,n.z,r.x,r.y,n.z),a(r.x,r.y,n.z,r.x,r.y,r.z),a(r.x,r.y,r.z,n.x,r.y,r.z),a(n.x,r.y,r.z,n.x,r.y,n.z),a(n.x,n.y,n.z,n.x,r.y,n.z),a(r.x,n.y,n.z,r.x,r.y,n.z),a(r.x,n.y,r.z,r.x,r.y,r.z),a(n.x,n.y,r.z,n.x,r.y,r.z),yO}function xO(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function SO(){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 CO(e,t,n,r,i){let a=i??SO();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,kO(e,t,o),MO(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 OO(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var wO=new V,TO=new V,EO=new V,DO=new V;function OO(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(TO),t.getWorldDirection(EO),DO.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[TO.x,TO.y,TO.z],forward:[EO.x,EO.y,EO.z],up:[DO.x,DO.y,DO.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(wO),t._setSpatialPose({position:[wO.x,wO.y,wO.z],listener:n})}function kO(e,t,n){let r=t;if(e instanceof Dy){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&&e instanceof $C&&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 LC&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof Yb&&n.cameras.push(e),r=i}else xO(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)kO(t,r,n);if(e instanceof Dy){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,jO(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var AO=new WeakSet;function jO(e){if(AO.has(e))return;AO.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof Yb)&&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 MO(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&&MO(i,t)}}var NO=`
7346
+ }`};var KD=[`type`,`sunPosition`,`elevationDeg`,`azimuthDeg`,`turbidity`,`rayleigh`],qD=[`color`,`near`,`far`],JD=[`coverage`,`density`,`base`,`top`,`color`,`shadeColor`,`speed`,`scale`],YD=[`threshold`,`strength`],XD=[`mapSize`,`radius`,`static`],ZD=[1024,2048],QD=2,$D=1,eO=50,tO=800,nO=`#cfd8e0`,rO=Math.PI/180;function iO(e){return{exposure:cO(e?.exposure),sky:lO(e?.sky),fog:uO(e?.fog,e?.sky!==void 0),clouds:dO(e?.clouds),bloom:fO(e?.bloom),shadows:pO(e?.shadows)}}function aO(e,t){let n=(90-e)*rO,r=t*rO;return[Math.sin(n)*Math.sin(r),Math.cos(n),Math.sin(n)*Math.cos(r)]}function oO(e){let[t,n,r]=e.sunPosition,i=Math.hypot(t,n,r)||1;return[t/i,n/i,r/i]}function sO(e){let t=[191,213,232],n=[233,228,217],r=[242,201,150],i=gO((e.turbidity-QD)/8),a=oO(e),o=gO((18-Math.asin(hO(a[1],-1,1))/rO)/18)*.8,s=e=>Math.round(_O(_O(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 cO(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new y(`BAD_FORMAT`,`environment.exposure must be a finite number > 0 (tone-mapping exposure, default 1), got ${JSON.stringify(e)}.`,{prop:`exposure`});return e}function lO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!KD.includes(e))throw new y(`BAD_FORMAT`,`environment.sky has unknown key '${e}'. Valid keys: [${KD.join(`, `)}].`,{prop:`sky`,validOptions:KD});if(t.type!==void 0&&t.type!==`atmosphere`)throw new y(`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 y(`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 y(`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=mO(t.elevationDeg,32,`sky.elevationDeg`),n=mO(t.azimuthDeg,135,`sky.azimuthDeg`);if(e<-90||e>90)throw new y(`BAD_FORMAT`,`environment.sky.elevationDeg must be in [-90, 90] (degrees above the horizon), got ${e}.`,{prop:`sky`});r=aO(e,n)}let i=mO(t.turbidity,QD,`sky.turbidity`);if(i<=0)throw new y(`BAD_FORMAT`,`environment.sky.turbidity must be > 0 (atmospheric haze; 2 ≈ clear day), got ${i}.`,{prop:`sky`});let a=mO(t.rayleigh,$D,`sky.rayleigh`);if(a<0)throw new y(`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 uO(e,t){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!qD.includes(e))throw new y(`BAD_FORMAT`,`environment.fog has unknown key '${e}'. Valid keys: [${qD.join(`, `)}].`,{prop:`fog`,validOptions:qD});if(n.color!==void 0&&typeof n.color!=`string`)throw new y(`BAD_FORMAT`,`environment.fog.color must be a hex color string, got ${JSON.stringify(n.color)}.`,{prop:`fog`});let r=mO(n.near,eO,`fog.near`),i=mO(n.far,tO,`fog.far`);if(r<0)throw new y(`BAD_FORMAT`,`environment.fog.near must be >= 0 meters, got ${r}.`,{prop:`fog`});if(i<=r)throw new y(`BAD_FORMAT`,`environment.fog.far must be > near (got near ${r}, far ${i}).`,{prop:`fog`});return{color:n.color??(t?``:nO),near:r,far:i}}function dO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!JD.includes(e))throw new y(`BAD_FORMAT`,`environment.clouds has unknown key '${e}'. Valid keys: [${JD.join(`, `)}].`,{prop:`clouds`,validOptions:JD});for(let e of[`color`,`shadeColor`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw new y(`BAD_FORMAT`,`environment.clouds.${e} must be a hex color string, got ${JSON.stringify(t[e])}.`,{prop:`clouds`});let n=mO(t.coverage,.5,`clouds.coverage`);if(n<0||n>1)throw new y(`BAD_FORMAT`,`environment.clouds.coverage must be in [0, 1] (how much sky is cloudy), got ${n}.`,{prop:`clouds`});let r=mO(t.density,1,`clouds.density`);if(r<0)throw new y(`BAD_FORMAT`,`environment.clouds.density must be >= 0 (optical thickness), got ${r}.`,{prop:`clouds`});let i=mO(t.base,120,`clouds.base`),a=mO(t.top,320,`clouds.top`);if(a<=i)throw new y(`BAD_FORMAT`,`environment.clouds.top must be > base (got base ${i}, top ${a}).`,{prop:`clouds`});let o=mO(t.speed,1,`clouds.speed`),s=mO(t.scale,240,`clouds.scale`);if(s<=0)throw new y(`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 fO(e){if(e===void 0)return null;if(typeof e!=`object`||!e||Array.isArray(e))throw new y(`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(!YD.includes(e))throw new y(`BAD_FORMAT`,`environment.bloom has unknown key '${e}'. Valid keys: [${YD.join(`, `)}].`,{prop:`bloom`,validOptions:YD});let n=mO(t.threshold,1,`bloom.threshold`);if(n<0||n>8)throw new y(`BAD_FORMAT`,`environment.bloom.threshold must be in [0, 8] (linear-HDR luminance; 1 = white), got ${n}.`,{prop:`bloom`});let r=mO(t.strength,.8,`bloom.strength`);if(r<0)throw new y(`BAD_FORMAT`,`environment.bloom.strength must be >= 0, got ${r}.`,{prop:`bloom`});return{threshold:n,strength:r}}function pO(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 y(`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(!XD.includes(e))throw new y(`BAD_FORMAT`,`environment.shadows has unknown key '${e}'. Valid keys: [${XD.join(`, `)}].`,{prop:`shadows`,validOptions:XD});let n=t.mapSize===void 0?2048:t.mapSize;if(!ZD.includes(n))throw new y(`BAD_FORMAT`,`environment.shadows.mapSize must be one of [${ZD.join(`, `)}], got ${JSON.stringify(t.mapSize)}.`,{prop:`shadows`,validOptions:ZD.map(String)});let r=mO(t.radius,1,`shadows.radius`);if(r<0)throw new y(`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 y(`BAD_FORMAT`,`environment.shadows.static must be a boolean, got ${JSON.stringify(t.static)}.`,{prop:`shadows`});return{mapSize:n,radius:r,static:i}}function mO(e,t,n){if(e===void 0)return t;if(typeof e!=`number`||!Number.isFinite(e))throw new y(`BAD_FORMAT`,`environment.${n} must be a finite number, got ${JSON.stringify(e)}.`,{prop:n});return e}function hO(e,t,n){return Math.min(Math.max(e,t),n)}function gO(e){return hO(e,0,1)}function _O(e,t,n){return e+(t-e)*n}var vO=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,yO={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 bO(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=yO[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(yO).join(`, `)}.`);return`${vO}/${t}`}return null}var xO=75,SO=class{scene;ambient=new il(`#ffffff`,0);envKey=null;config=iO(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new sa(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new W;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?oO(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get sceneFog(){return this.scene.fog instanceof sa?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=iO(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)*CO(e?.iblIntensity),e?.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new W(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=xO,t.top=xO,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 sa(`#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=bO(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new WD().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 GD,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 iu(t),r=new ca;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?sO(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 CO(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new y(`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 wO=new Ca,TO=new V,EO=.4,DO=new Float32Array(72);function OO(e){if(!(e instanceof Dy))return null;let t=e._ensureObject3D();if(t.updateWorldMatrix(!0,!0),wO.setFromObject(t),wO.getSize(TO),!Number.isFinite(TO.x)||TO.x===0&&TO.y===0&&TO.z===0){let e=new V().setFromMatrixPosition(t.matrixWorld);wO.min.set(e.x-EO,e.y-EO,e.z-EO),wO.max.set(e.x+EO,e.y+EO,e.z+EO)}else wO.expandByScalar(.02);let{min:n,max:r}=wO,i=0,a=(e,t,n,r,a,o)=>{DO[i++]=e,DO[i++]=t,DO[i++]=n,DO[i++]=r,DO[i++]=a,DO[i++]=o};return a(n.x,n.y,n.z,r.x,n.y,n.z),a(r.x,n.y,n.z,r.x,n.y,r.z),a(r.x,n.y,r.z,n.x,n.y,r.z),a(n.x,n.y,r.z,n.x,n.y,n.z),a(n.x,r.y,n.z,r.x,r.y,n.z),a(r.x,r.y,n.z,r.x,r.y,r.z),a(r.x,r.y,r.z,n.x,r.y,r.z),a(n.x,r.y,r.z,n.x,r.y,n.z),a(n.x,n.y,n.z,n.x,r.y,n.z),a(r.x,n.y,n.z,r.x,r.y,n.z),a(r.x,n.y,r.z,r.x,r.y,r.z),a(n.x,n.y,r.z,n.x,r.y,r.z),DO}function kO(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function AO(){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 jO(e,t,n,r,i){let a=i??AO();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,LO(e,t,o),BO(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 IO(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}var MO=new V,NO=new V,PO=new V,FO=new V;function IO(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(NO),t.getWorldDirection(PO),FO.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[NO.x,NO.y,NO.z],forward:[PO.x,PO.y,PO.z],up:[FO.x,FO.y,FO.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(MO),t._setSpatialPose({position:[MO.x,MO.y,MO.z],listener:n})}function LO(e,t,n){let r=t;if(e instanceof Dy){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&&e instanceof sw&&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 GC&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof nx&&n.cameras.push(e),r=i}else kO(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)LO(t,r,n);if(e instanceof Dy){let t=e._ensureObject3D();e.static&&!n.ignoreStatic?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,zO(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var RO=new WeakSet;function zO(e){if(RO.has(e))return;RO.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof nx)&&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 BO(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&&BO(i,t)}}var VO=`
7347
7347
  varying vec2 vUv;
7348
7348
  void main() {
7349
7349
  vUv = uv;
7350
7350
  gl_Position = vec4(position.xy, 0.0, 1.0);
7351
7351
  }
7352
- `,PO=`
7352
+ `,HO=`
7353
7353
  precision highp float;
7354
7354
  varying vec2 vUv;
7355
7355
  uniform sampler2D tColor;
@@ -7402,9 +7402,9 @@ void main() {
7402
7402
  }
7403
7403
  gl_FragColor = color;
7404
7404
  }
7405
- `;function FO(){let e=new tc({vertexShader:NO,fragmentShader:PO,depthTest:!1,depthWrite:!1,uniforms:{tColor:{value:null},tDepth:{value:null},uInvViewProj:{value:new U},uCameraPos:{value:new V},uWaterLevel:{value:0},uTime:{value:0},uCausticColor:{value:new W(`#cdeeff`)},uCausticIntensity:{value:.55},uCausticScale:{value:.32},uMaxDist:{value:22}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var IO=class{viewOverride=null;overrideCam=new Xc(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new ca;environment=new mO(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;syncScratch=SO();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 vy;let t=ut(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2)},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio});this.webgl=new Qf({canvas:e.canvas,antialias:t.antialias}),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Ts(new K,new ps({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Ts(new K,new ps({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())}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?bO(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new G(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of lp(`3d`))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new G(e,3))}render(){let e=this.engine.scene;if(!e)return;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}=CO(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(RO.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(UO),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i));let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(LO);(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=BO.setFromMatrixPosition(o.matrixWorld).sub(VO.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;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):h&&!p?this.renderWithBloom(i,h):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t){let n=this.webgl.getDrawingBufferSize(LO),r=Math.max(1,n.x),i=Math.max(1,n.y),a=Math.max(1,Math.ceil(r/2)),o=Math.max(1,Math.ceil(i/2));if(this.bloomTarget&&(this.bloomTarget.width!==r||this.bloomTarget.height!==i)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Ci(r,i,{type:$t}),this.bloomBrightTarget=new Ci(a,o,{type:$t}),this.bloomBlurTarget=new Ci(a,o,{type:$t})),!this.bloomBrightScene){let e=TD();this.bloomBrightScene=new ca,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=ED();this.bloomBlurScene=new ca,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=DD();this.bloomCompositeScene=new ca,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let s=this.bloomBrightTarget,c=this.bloomBlurTarget;this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e);let l=this.bloomBrightUniforms;l.tScene.value=this.bloomTarget.texture,l.uThreshold.value=t.threshold,this.webgl.setRenderTarget(s),this.webgl.render(this.bloomBrightScene,e);let u=this.bloomBlurUniforms;u.tTex.value=s.texture,u.uDir.value.set(1/a,0),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e),u.tTex.value=c.texture,u.uDir.value.set(0,1/o),this.webgl.setRenderTarget(s),this.webgl.render(this.bloomBlurScene,e);let d=this.bloomCompositeUniforms;d.tScene.value=this.bloomTarget.texture,d.tBloom.value=s.texture,d.uStrength.value=t.strength,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(LO),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 Is(i,a);e.type=Qt,this.cloudsTarget=new Ci(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ci(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ci(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=ND();this.cloudsScene=new ca,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=MD();this.cloudsBlurScene=new ca,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=PD();this.cloudsCompositeScene=new ca,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(LO),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 Is(r,i);e.type=Qt,this.causticsTarget=new Ci(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=FO();this.causticsScene=new ca,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,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(zO.set(e,t,n).project(r),{x:(zO.x+1)/2*this.lastSize.w,y:(1-zO.y)/2*this.lastSize.h,behind:zO.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;GO.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),WO.setFromCamera(GO,n);let r=WO.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}}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(HO):HO.identity();return{right:new V(1,0,0).applyQuaternion(t),up:new V(0,1,0).applyQuaternion(t),forward:new V(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){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()}},LO=new z,RO=new V,zO=new V,BO=new V,VO=new V,HO=new B,UO=new V,WO=new Al,GO=new z,KO=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Qy,WATER_MAX_RIPPLES:()=>8,enablePhysics3D:()=>_b}),qO=new WeakMap,JO=class e{account;roomId;roomState=new t;allUserStates=new t;userJoined=new t;userLeft=new t;globalState=new t;globalMyState=new t;asset=new t;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 qO.get(e)??null}static async create(t,n={}){await qO.get(t)?.dispose();let r=n.transport??await $O(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 qO.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 n=this.messageSignals.get(e);return n||(n=new t,this.messageSignals.set(e,n),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>n?.emit(e)))),n}collection(e){let n=this.collectionSignals.get(e);return n||(n=new t,this.collectionSignals.set(e,n),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,t=>{this.latestCollections.set(e,t),n?.emit(t)}))),n}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let n=this.globalMessageSignals.get(e);if(!n){n=new t,this.globalMessageSignals.set(e,n);let r=this.server.onGlobalMessage?.(e,e=>n?.emit(e));r&&this.subs.push(r)}return n}globalCollection(e){let n=this.globalCollectionSignals.get(e);if(!n){n=new t,this.globalCollectionSignals.set(e,n);let r=this.server.subscribeGlobalCollection?.(e,t=>{this.latestGlobalCollections.set(e,t),n?.emit(t)});r&&this.subs.push(r)}return n}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 y(`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]),qO.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=YO(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=ZO(n,e);t!==void 0&&(fe(this.lastSent.get(e)??null,t)||(o[e]=A(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,A(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function YO(e,t=!1){let n=[];if(XO(e,n),t&&n.length>1)throw new y(`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 XO(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)XO(n,t)}function ZO(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 QO(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 $O(e){let{createAgent8Server:t}=await mp(async()=>{let{createAgent8Server:e}=await import(`./agent8-B0ZGx-N1.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var ek=class extends Fe{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=JO.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=Ct(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=tk(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&QO(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 tk(e){return e.replace(/[/%]/g,`_`)||`remote`}function nk(){lt(),j(ek)}var rk=80,ik=` `;function ak(e){return`${ok(e,0)}\n`}function ok(e,t){if(typeof e!=`object`||!e)return JSON.stringify(e);let n=sk(e);if(t*2+n.length<=rk)return n;let r=ik.repeat(t+1),i=ik.repeat(t);if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>r+ok(e,t+1)).join(`,
7406
- `)}\n${i}]`;let a=Object.entries(e);return a.length===0?`{}`:`{\n${a.map(([e,n])=>`${r}${JSON.stringify(e)}: ${ok(n,t+1)}`).join(`,
7407
- `)}\n${i}}`}function sk(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(sk).join(`, `)}]`;let t=Object.entries(e);return t.length===0?`{}`:`{ ${t.map(([e,t])=>`${JSON.stringify(e)}: ${sk(t)}`).join(`, `)} }`}async function ck(e){if(!e.ok)throw Error(`HTTP ${e.status} — ${await e.text()}`);return e}async function lk(){return await(await ck(await fetch(`/api/meta`))).json()}async function uk(){return await(await ck(await fetch(`/api/scenes`))).json()}async function dk(e){return await(await ck(await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})}))).json()}function fk(e){return e?`/api/scene?file=${encodeURIComponent(e)}`:`/api/scene`}async function pk(e){return await(await ck(await fetch(fk(e)))).json()}async function mk(e,t){await ck(await fetch(fk(t),{method:`PUT`,body:ak(e)}))}var hk=localStorage.getItem(`incanto-editor-lang`)??`en`,gk=new Set;function _k(){return hk}function vk(e){hk=e,localStorage.setItem(`incanto-editor-lang`,e);for(let e of gk)e()}function yk(e){gk.add(e)}function bk(e){return e[hk]}var xk={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`]}},Sk={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 Ck(e){let t=xk[Sk[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 wk(){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 Tk=[{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`]}],Ek=new Set,Dk=null,Ok=null;function kk(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 Ak(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 jk(e){let t=e.assets.length;for(let n of e.folders.values())t+=jk(n);return t}function Mk(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(Wk(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),Gk(s,i.type??``)}),Dk===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(kk(a,r=>{Dk=null,t.renameAssetKey(e,n+r)},()=>{Dk=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(),Dk=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=Ek.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(wk());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),Ok===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,kk(e.name,n=>{Ok=null,t.renameGroup(e.path,i+n)},()=>{Ok=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(),Ok=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${jk(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{Ek.has(e.path)?Ek.delete(e.path):Ek.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=Ak(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function Nk(e,t,n){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(Yk(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(zk(`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 Lk(e,t);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(Yk(`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(Bk(`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 r=t.selectedAsset;if(r===null)return!1;let i=t.working.assets??{};if(!(r in i))return!1;e.appendChild(Yk(`ASSET — ${String(i[r].type??`?`)}`)),e.appendChild(Kk(r)),e.appendChild(qk(t,r)),e.appendChild(Pk(t,i,r));let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost danger`,a.textContent=`delete asset`,a.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete i[r],Object.keys(i).length===0&&delete t.working.assets})}),e.appendChild(a),!0}function Pk(e,t,n){let r=t[n],i=document.createElement(`div`);i.className=`asset-editor`;let a=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,o=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,s=Bk(`name`,a,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==a&&e.renameAssetKey(n,o+r)});Jk(s.querySelector(`input`)),i.appendChild(s),i.appendChild(Bk(`url`,String(r.url??``),t=>{e.mutate(()=>{r.url=t.trim()})}));let c=document.createElement(`div`);c.className=`muted-note`,c.textContent=`meta (key · value)`,i.appendChild(c);for(let[t,n]of Object.entries(r))t===`type`||t===`url`||i.appendChild(Fk(e,r,t,n));return i.appendChild(Ik(e,r)),i}function Fk(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]=Vk(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 Ik(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]=Vk(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function Lk(e,t){return e.appendChild(Yk(`NEW ASSET`)),e.appendChild(Rk(t)),!0}function Rk(e){let t=document.createElement(`div`);t.className=`asset-editor`;let n=document.createElement(`select`);for(let e of Tk){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,n.appendChild(t)}t.appendChild(zk(`type`,n));let r=document.createElement(`input`);r.placeholder=`(optional) characters`,r.className=`mono`,r.value=e.newAssetGroup;let i=`asset-groups-list`;r.setAttribute(`list`,i);let a=document.createElement(`datalist`);a.id=i;let o=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&o.add(t.slice(0,e))}for(let t of e.pendingGroups)o.add(t);for(let e of o){let t=document.createElement(`option`);t.value=e,a.appendChild(t)}t.appendChild(zk(`group`,r)),t.appendChild(a);let s=document.createElement(`input`);s.placeholder=`coin`,s.className=`mono`,Jk(s),t.appendChild(zk(`key`,s));let c=document.createElement(`input`);c.placeholder=`/textures/coin.png · https://… · data:…`,c.className=`mono`,t.appendChild(zk(`url`,c));let l=document.createElement(`textarea`);l.rows=2,l.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,t.appendChild(l);let u=document.createElement(`button`);u.type=`button`,u.className=`primary`,u.textContent=`add`,u.addEventListener(`click`,()=>{let t=s.value.trim().replace(/^\$/,``);if(!t)return;let i=r.value.trim().replace(/\/+$/,``),a=i?`${i}/${t}`:t,o=null,u=l.value.trim();if(u)try{o=JSON.parse(u)}catch{l.classList.add(`invalid`);return}else c.value.trim()&&(o={type:n.value,url:c.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 d=document.createElement(`div`);return d.className=`pop-actions`,d.appendChild(u),t.appendChild(d),t}function zk(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 Bk(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),zk(e,r)}function Vk(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 Hk={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`},Uk={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 Wk(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`,Hk[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function Gk(e,t){document.querySelector(`.balloon`)?.remove();let n=Uk[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=bk(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 Kk(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 qk(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 Jk(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function Yk(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 Xk=window.parent!==window,Zk=new URLSearchParams(window.location.search).get(`parentOrigin`),Qk=!1;function $k(e){if(Xk){if(!Zk){Qk||(Qk=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,Zk)}}var eA={ready(e,t,n){$k({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){$k({type:`incanto-editor:open`,input:e,output:t})},change(e){$k({type:`incanto-editor:change`,dirty:e})},save(e,t,n){$k({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){$k({type:`incanto-editor:error`,message:e})}},tA=[[`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`]],nA=[...tA,[`Other`,e=>tA.every(([,t])=>!t(e))]],rA={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 editor shows and edits these links but the code lives in the game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 에디터는 이 연결을 보여주고 편집하지만 코드는 게임에 있습니다.`}},{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 아바타에 자동 리타게팅됩니다.`}}]},Z=(e,t,...n)=>({type:e,summary:t,body:n}),iA=[{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:[Z(`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 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Z(`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 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Z(`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로 캔버스 위에 올립니다.`}),Z(`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는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Z(`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로 작은 캡션을 붙입니다.`}),Z(`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) 시그널을 냅니다.`}),Z(`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()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Z(`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를 확인하세요.`}),Z(`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:[Z(`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로 서브트리 표시를 제어합니다.`}),Z(`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로 정해집니다.`}),Z(`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가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Z(`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) 칸의 좌상단이 노드 원점에 걸립니다.`}),Z(`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)를 발산합니다.`}),Z(`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인 카메라가 실제 시점이 됩니다.`}),Z(`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를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`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).`}),Z(`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:[Z(`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:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Z(`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를 권합니다.`}),Z(`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)는 길을 막지 않으면서 트리거를 발사합니다.`}),Z(`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")로 거릅니다.`}),Z(`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는 의도 그대로의 숫자입니다.`}),Z(`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:[Z(`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은 축별. 자식이 상속합니다.`}),Z(`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.`}),Z(`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 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Z(`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).',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨).'}),Z(`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로 색·투명도.`}),Z(`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 연결).`}),Z(`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(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Z(`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)으로 정확한 렌더 결과를 미리 보세요.`}),Z(`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와 함께 쓰세요.`}),Z(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Z(`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] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`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'}를 쓰세요.`}),Z(`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를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Z(`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.`,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가 배치를 재현 가능하게 합니다.`}),Z(`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.`,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.`}),Z(`Tree3D`,{en:`Procedural ez-tree groves — branchy trunks, textured leaves.`,ko:`프로시저럴 ez-tree 나무 — 가지 달린 줄기와 텍스처 잎까지.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Z(`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:[Z(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry.`,ko:`바닥·벽·레벨 지형.`}),Z(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Z(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Z(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Z(`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 같은 의도 수준의 숫자만 만집니다.`}),Z(`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면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Z(`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:[Z(`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를 발산합니다.`})]}],aA=`overview`,oA=null;function sA(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),uA()}function cA(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function lA(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&cA()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,cA))}function uA(){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${aA===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{aA=t,oA=null,uA()}),e.appendChild(r)};n(`overview`,bk({en:`Overview`,ko:`개요`}));for(let e of iA)n(e.id,bk(e.label));if(t.textContent=``,aA===`overview`){dA(t);return}let r=iA.find(e=>e.id===aA);r&&fA(t,r)}function dA(e){let t=document.createElement(`h2`);t.textContent=bk(rA.title),e.appendChild(t);for(let t of rA.sections){let n=document.createElement(`h3`);n.textContent=bk(t.heading);let r=document.createElement(`p`);r.textContent=bk(t.text),e.append(n,r)}}function fA(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=bk(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${oA===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(Ck(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=bk(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{oA=oA===n.type?null:n.type,uA()}),t.appendChild(r),oA===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=bk(t),e.appendChild(n)}e.appendChild(pA(n.type)),t.appendChild(e)}e.appendChild(t)}}function pA(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[bk({en:`prop`,ko:`prop`}),bk({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=_e(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 Q(e){return Math.round(e*100)/100}function mA(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 hA(e,t,n,r,i,a){let o=Q(r.range(i[0],i[1])),s=Q(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,Q(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,Q(o*s),Q(o*r.range(.8,1.1))],material:{color:a??gA(r),roughness:1},castShadow:!0}}}function gA(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function _A(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(e*.8),Q(e*1.5),Q(e*.6)],intensity:1,castShadow:!0,shadowArea:Q(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-e*.8),Q(e*.8),Q(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function vA(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function yA(e,t,n){return Math.min(Math.max(e,t),n)}var bA=[`boxes`,`ruins`,`garden`],xA=.5,SA=.1,CA=2,wA={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 TA(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!bA.includes(o))throw new y(`BAD_FORMAT`,`generateArena theme must be one of [${bA.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...bA]});let s=wA[o],c=new b(t),l=[mA(`Floor`,[n,SA,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+xA*2,i,xA],f=[xA,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(mA(`Wall1`,d,[0,u,-(r+xA)/2],p),mA(`Wall2`,d,[0,u,(r+xA)/2],p),mA(`Wall3`,f,[-(n+xA)/2,u,0],p),mA(`Wall4`,f,[(n+xA)/2,u,0],p)),o===`ruins`?l.push(...DA(c,s,n,r,i,a)):l.push(...EA(c,s,n,r,i,a,o)),o===`garden`&&l.push(...OA(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(m*.8),Q(m*1.5),Q(m*.6)],intensity:1,castShadow:!0,shadowArea:Q(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-m*.8),Q(m*.8),Q(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,Q(i+2),0],intensity:.5,color:`#fff3d6`,range:Q(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function EA(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=[Q(e.range(.8,2.6)),Q(e.range(.8,Math.max(1.2,i*.8))),Q(e.range(.8,2.6))],l=Q(e.range(-(n/2-CA),n/2-CA)),u=Q(e.range(-(r/2-CA),r/2-CA));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=Q(l/t*(c+1.5+e.range(0,2))),u=Q(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(mA(`Obstacle${o}`,a,[l,Q(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function DA(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-CA*2,u=r-CA*2,d=0;for(let n=0;n<s&&d<a;n++){let r=Q(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=Q((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=Q(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=Q(e.range(.8,1.2));o.push(mA(`Obstacle${d}`,[u,s,u],[a,Q(s/2),Q(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function OA(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=Q(e.range(-a,a)),s=Q(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=Q(o/c*(i+r/2+.5)),s=Q(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=Q(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=Q(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:[Q(i*2),Q(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var kA=32,AA=[4,8],jA=`#332f3a`,MA=`#6b6357`;function NA(e){let{seed:t,rooms:n=5}=e,[r,i]=vA(e.size,[960,720]),a=Math.max(8,Math.floor(r/kA)),o=Math.max(8,Math.floor(i/kA)),s=new b(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(AA[0],AA[1]),t=s.int(AA[0],AA[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=>PA(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]=FA(c[e-1]),[r,i]=FA(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*kA)/2,m=-(o*kA)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*kA,m+(t.y+t.h/2)*kA],size:[t.w*kA,t.h*kA],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,jA));for(let e of d)g.push(h(e.name,e.rect,jA));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*kA,kA];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*kA,m+(e+.5)*kA],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:MA}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function PA(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 FA(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var IA=[[0,-1],[1,0],[0,1],[-1,0]];function LA(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 IA){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 RA=[`stone`,`hedge`,`canyon`],zA=.1,BA=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,VA=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,HA={stone:{wall:{color:`#e8e2d8`,map:`${BA}/blocks.png`,normalMap:`${BA}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${VA}/stone.png`,normalMap:`${VA}/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:`${VA}/grass.png`,normalMap:`${VA}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${VA}/grass.png`,normalMap:`${VA}/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:`${VA}/stone.png`,normalMap:`${VA}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${VA}/sand.png`,normalMap:`${VA}/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 UA(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[Q(t/e.tile),Q(n/e.tile)]}}var WA=10;function GA(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!RA.includes(o))throw new y(`BAD_FORMAT`,`generateMaze theme must be one of [${RA.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...RA]});let s=HA[o],c=new b(t),l=LA(c,n,r),u=2*n+1,d=2*r+1,f=Q(u*i),p=Q(d*i),m=(e,t)=>[Q((e+.5)*i-f/2),Q((t+.5)*i-p/2)],h=[mA(`Floor`,[f,zA,p],[0,-.1/2,0],{material:UA(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=Q(n*i);h.push(mA(`Wall${_}`,[r,a,i],[Q((t+n/2)*i-f/2),Q(a/2),Q((e+.5)*i-p/2)],{material:UA(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...KA(g,i,a,f,p,s.cap)),h.push(...qA(c,l,i,a,m,s)),o===`hedge`?(h.push(...ZA(c,g,i,a,m)),h.push(...QA(c,l,i,m,n,r))):o===`canyon`&&h.push(...$A(c,g,i,a,m)),h.push(...YA(l,i,a,m,s)),h.push(..._A(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,Q((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function KA(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[Q(e.run*t+.16),.12,Q(t+.16)],position:[Q((e.gx+e.run/2)*t-r/2),Q(n+.06),Q((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function qA(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(WA,o.length),l=[],u=new Set,d=Q(n*1.2),f=Q(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(JA(`Pillar${t}`,c,p,d,f,a))}return l}function JA(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,Q(i/2),n],material:{...UA(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function YA(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=Q(t*1.1),c=Q(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 JA(`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:[Q(t*.96),.04,Q(t*.96)],position:[a,.02,o],material:{...UA(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var XA=10;function ZA(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,XA).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:[Q(t.run*n*.92),Q(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[Q((s+c)/2),r,o]}}})}function QA(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=Q(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 $A(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=hA(s,c,l,e,[.3,Q(n*.35)],`#8f7355`),d=u.props?.position;d[1]=Q(d[1]+r),a.push(u)}return a}var ej=`#23222b`,tj=`#5f6672`;function nj(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=LA(new b(t),n,r),o=2*n+1,s=2*r+1,c=Q(o*i),l=Q(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:ej}}],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=[Q(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[Q((t+n/2)*i-c/2),Q((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:tj}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var rj=16,ij=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function aj(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 b(t),c=[],l=Q(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(oj(e,u,d,l,s.pick(ij))),e!==n);e++){let e=Q(s.range(r[0],r[1])),t=Q(s.range(i[0],i[1]));u=Q(u+l/2+t+e/2),d=Q(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function oj(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,rj]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,rj],color:i}}]}}var sj=[3,5],cj=3,lj={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function uj(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=vA(e.area,[60,60]),o=new b(t),s=[];for(let e=1;e<=n;e++){let t=o.int(sj[0],sj[1]),n=[];for(let e=1;e<=t;e++){let r=Q(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[Q((e-(t+1)/2)*o.range(1,1.6)),Q(o.range(-.3,.3)),Q(o.range(-.6,.6))],scale:[Q(r*o.range(1.1,1.6)),Q(r*.55),r],material:lj}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[Q(o.range(-i/2,i/2)),Q(r+o.range(-3,cj)),Q(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var dj=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],fj=128,pj=20,mj=.8,hj=.12,gj={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 _j(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=gj[n];if(!a)throw new y(`BAD_FORMAT`,`generateTerrain theme must be one of [${dj.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...dj]});let o=e.maxHeight||a.maxHeight,s=new b(t),c=n===`island`,l=e=>Ry({width:r,depth:r,segsX:fj,segsZ:fj,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:c}),u=l(o);if(c)for(let e=0;e<3;e++){let e=yj(u)-pj,t=u.maxHeight-u.minHeight,n=u.minHeight+hj*t;if(e+mj<=n)break;let r=pj-mj,i=yj(u)-u.minHeight-hj*t;o=Q(o*Math.min(r/i*.95,.9)),u=l(o)}let d=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:o,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail}}}]}],f=n===`wetland`;if(c)d.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,vj(u),0],opacity:1}});else if(f){let e=u.maxHeight-u.minHeight||1,t=Q(u.minHeight+.22*e);d.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=Q(u.minHeight+.1*(u.maxHeight-u.minHeight));d.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return d.push(...Fj(n,s,u,r)),c&&d.push(uj({seed:s.int(1,1e9),count:6,area:r,altitude:Math.round(u.maxHeight+12)})),d.push(..._A(r).map((e,t)=>Ij(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:d}}function vj(e){let t=yj(e)-pj,n=e.minHeight+hj*(e.maxHeight-e.minHeight);return Q(Math.max(Math.min(t+mj,n),t+.55))}function yj(e){let t=-1/0,n=e.width/2,r=e.depth/2;for(let i=0;i<=fj;i++){let a=-n+i/fj*e.width,o=-r+i/fj*e.depth;t=Math.max(t,e.baseHeight(a,-r),e.baseHeight(a,r),e.baseHeight(-n,o),e.baseHeight(n,o))}return t}function bj(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=Q(e.range(-r,r)),s=Q(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 xj=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],Sj=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],Cj={canopy:`#9aa052`,trunk:`#8a6a44`},wj={canopy:`#39513f`,trunk:`#5a5650`};function Tj(e,t){return e===`conifer`?t.pick(xj):e===`broadleaf`?t.pick(Sj):null}function Ej(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=Tj(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:Q(n.range(a[0],a[1])),position:[t.x,Q(t.y-o),t.z],...s}}}function Dj(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,Q(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function Oj(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,Q(t.y+.02),t.z]}}}function kj(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,Q(t.y+.02),t.z]}}}function Aj(e,t,n,r){return e.map((e,i)=>{let a=hA(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=Q(o[1]+e.y),a})}function jj(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 Mj(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 Nj(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 Pj=[`#6f5b41`,`#7a644a`,`#665439`];function Fj(e,t,n,r){let i=[];switch(e){case`island`:{let e=bj(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=bj(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`conifer`)));let r=bj(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...Aj(r,t,[.6,1.8]));break}case`plains`:{let e=bj(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`broadleaf`)));let r=bj(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...Aj(r,t,[.4,1.2]));break}case`desert`:{let e=bj(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`dead`)));let r=bj(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...Aj(r,t,[.5,1.6]));break}case`meadow`:{let e=Q(r*.09),a=bj(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>Dj(`Carpet${r+1}`,n,t,e,30)));let o=Q(r*.07),s=bj(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>kj(`Flowers${n+1}`,e,t,o,`sparse`)));let c=bj(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>Ej(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=bj(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...Aj(l,t,[.3,.9]));break}case`forest`:{let e=Q(r*.12),a=r/2-8,o=tt(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=bj(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)=>Ej(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(Ej(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=bj(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>Ej(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=bj(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>Ej(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=bj(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>Ej(`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=Q(yA(e.x+Math.cos(o)*s,-a,a)),u=Q(yA(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,Q(n.heightAt(l,u)+.02),u]}}))});let m=Q(r*.08),h=bj(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>Dj(`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=Q(yA(r.x+Math.cos(o)*s,-a,a)),l=Q(yA(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:Q(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,Q(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),Q(t.range(81,97))]}})}bj(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=Q(t.range(.16,.28)),a=Q(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,Q(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(Pj),roughness:1},castShadow:!0}})});let _=bj(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...Aj(_,t,[.3,1],jj));let v=Q(e*.75),y=bj(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-Q(v/Math.SQRT2)});i.push(...y.map((e,n)=>Dj(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=Q(e*.45),x=bj(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-Q(b/Math.SQRT2)});i.push(...x.map((e,n)=>kj(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=bj(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:Cj})));let a=Q(r*.09),o=bj(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>Dj(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=bj(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...Aj(s,t,[.4,1.4]));let c=bj(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>Ej(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=bj(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:wj})));let r=bj(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...Aj(r,t,[.5,1.8],Mj));break}case`wetland`:{let e=Q(r*.08),a=bj(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>Oj(`Reeds${r+1}`,n,t,e,4)));let o=Q(r*.08),s=bj(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Dj(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=bj(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>Ej(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=bj(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>Ej(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=bj(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...Aj(u,t,[.3,1],jj));break}case`volcanic`:{let e=bj(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>Ej(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=bj(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...Aj(r,t,[.4,1.8],Nj)),bj(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,Q(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,Q(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 Ij(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var Lj={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:[...bA]},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:[...dj]},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:[...RA]},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}}}},Rj={arena:TA,terrain:_j,maze:GA,maze2d:nj,dungeon2d:NA,platforms2d:aj};function zj(e,t){let n=Rj[e];if(!n){let t=Object.keys(Rj);throw new y(`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 Bj(e){return Object.entries(Lj).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function Vj(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 Hj(){return Math.floor(Math.random()*1e6)}var Uj=[],Wj=new Map,Gj=null;function Kj(e){let t=document.querySelector(`#generate`);t&&(Yj(e),t.removeAttribute(`hidden`))}function qj(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function Jj(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&qj()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,qj),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,qj),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>Xj(e)))}function Yj(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`;Uj=Bj(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=bk({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=Zj(bk({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of Uj){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=Zj(`seed`);Gj=document.createElement(`input`),Gj.type=`number`,Gj.step=`1`,Gj.value=String(Hj());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=bk({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{Gj&&(Gj.value=String(Hj()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(Gj,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=Uj.find(e=>e.name===o.value)??Uj[0];if(e){s.textContent=e.meta.description,c.textContent=``,Wj=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=Zj(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??``}`);Wj.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function Xj(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=Uj.find(e=>e.name===n?.value);if(!r||!Gj)return;let i={seed:Vj({type:`number`,default:Hj(),min:0},Gj.value)};for(let[e,t]of Wj){let n=r.meta.params[e];n&&(i[e]=Vj(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=zj(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=bk({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),Gj&&(Gj.value=String(Hj())),qj()}function Zj(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var Qj={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';
7405
+ `;function UO(){let e=new tc({vertexShader:VO,fragmentShader:HO,depthTest:!1,depthWrite:!1,uniforms:{tColor:{value:null},tDepth:{value:null},uInvViewProj:{value:new U},uCameraPos:{value:new V},uWaterLevel:{value:0},uTime:{value:0},uCausticColor:{value:new W(`#cdeeff`)},uCausticIntensity:{value:.55},uCausticScale:{value:.32},uMaxDist:{value:22}}}),t=new Mo(new Gs(2,2),e);return t.frustumCulled=!1,{mesh:t,uniforms:e.uniforms}}var WO=class{viewOverride=null;overrideCam=new Xc(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new ca;environment=new SO(this.threeScene);engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;syncScratch=AO();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 vy;let t=ut(e.engine.scene?.environment,{antialias:!0,pixelRatio:Math.min(globalThis.devicePixelRatio??1,2)},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio});this.webgl=new Qf({canvas:e.canvas,antialias:t.antialias}),this.webgl.setPixelRatio(t.pixelRatio),this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new Ts(new K,new ps({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new Ts(new K,new ps({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())}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?OO(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new G(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of lp(`3d`))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new G(e,3))}render(){let e=this.engine.scene;if(!e)return;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}=jO(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(KO.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(ZO),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i));let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(GO);(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=JO.setFromMatrixPosition(o.matrixWorld).sub(YO.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;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):h&&!p?this.renderWithBloom(i,h):this.webgl.render(this.threeScene,i)}renderWithBloom(e,t){let n=this.webgl.getDrawingBufferSize(GO),r=Math.max(1,n.x),i=Math.max(1,n.y),a=Math.max(1,Math.ceil(r/2)),o=Math.max(1,Math.ceil(i/2));if(this.bloomTarget&&(this.bloomTarget.width!==r||this.bloomTarget.height!==i)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Ci(r,i,{type:$t}),this.bloomBrightTarget=new Ci(a,o,{type:$t}),this.bloomBlurTarget=new Ci(a,o,{type:$t})),!this.bloomBrightScene){let e=ND();this.bloomBrightScene=new ca,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=PD();this.bloomBlurScene=new ca,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=FD();this.bloomCompositeScene=new ca,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let s=this.bloomBrightTarget,c=this.bloomBlurTarget;this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e);let l=this.bloomBrightUniforms;l.tScene.value=this.bloomTarget.texture,l.uThreshold.value=t.threshold,this.webgl.setRenderTarget(s),this.webgl.render(this.bloomBrightScene,e);let u=this.bloomBlurUniforms;u.tTex.value=s.texture,u.uDir.value.set(1/a,0),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e),u.tTex.value=c.texture,u.uDir.value.set(0,1/o),this.webgl.setRenderTarget(s),this.webgl.render(this.bloomBlurScene,e);let d=this.bloomCompositeUniforms;d.tScene.value=this.bloomTarget.texture,d.tBloom.value=s.texture,d.uStrength.value=t.strength,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(GO),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 Is(i,a);e.type=Qt,this.cloudsTarget=new Ci(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ci(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ci(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=VD();this.cloudsScene=new ca,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=BD();this.cloudsBlurScene=new ca,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=HD();this.cloudsCompositeScene=new ca,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(GO),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 Is(r,i);e.type=Qt,this.causticsTarget=new Ci(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=UO();this.causticsScene=new ca,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,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(qO.set(e,t,n).project(r),{x:(qO.x+1)/2*this.lastSize.w,y:(1-qO.y)/2*this.lastSize.h,behind:qO.z>1}):{x:0,y:0,behind:!0}}pick(e,t){let n=this.lastCamera;if(!n)return null;$O.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),QO.setFromCamera($O,n);let r=QO.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}}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(XO):XO.identity();return{right:new V(1,0,0).applyQuaternion(t),up:new V(0,1,0).applyQuaternion(t),forward:new V(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){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()}},GO=new z,KO=new V,qO=new V,JO=new V,YO=new V,XO=new B,ZO=new V,QO=new Al,$O=new z,ek=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Qy,WATER_MAX_RIPPLES:()=>8,enablePhysics3D:()=>_b}),tk=new WeakMap,nk=class e{account;roomId;roomState=new t;allUserStates=new t;userJoined=new t;userLeft=new t;globalState=new t;globalMyState=new t;asset=new t;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 tk.get(e)??null}static async create(t,n={}){await tk.get(t)?.dispose();let r=n.transport??await sk(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 tk.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 n=this.messageSignals.get(e);return n||(n=new t,this.messageSignals.set(e,n),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>n?.emit(e)))),n}collection(e){let n=this.collectionSignals.get(e);return n||(n=new t,this.collectionSignals.set(e,n),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,t=>{this.latestCollections.set(e,t),n?.emit(t)}))),n}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let n=this.globalMessageSignals.get(e);if(!n){n=new t,this.globalMessageSignals.set(e,n);let r=this.server.onGlobalMessage?.(e,e=>n?.emit(e));r&&this.subs.push(r)}return n}globalCollection(e){let n=this.globalCollectionSignals.get(e);if(!n){n=new t,this.globalCollectionSignals.set(e,n);let r=this.server.subscribeGlobalCollection?.(e,t=>{this.latestGlobalCollections.set(e,t),n?.emit(t)});r&&this.subs.push(r)}return n}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 y(`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]),tk.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t||t!==this.boundScene)return;this.sendAccumulator+=e*1e3;let n=rk(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=ak(n,e);t!==void 0&&(de(this.lastSent.get(e)??null,t)||(o[e]=j(t)))}if(!(this.sendAccumulator<i)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,j(t));this.sendAccumulator=0,this.setMyState({sync:o})}}};function rk(e,t=!1){let n=[];if(ik(e,n),t&&n.length>1)throw new y(`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 ik(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)ik(n,t)}function ak(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 ok(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 sk(e){let{createAgent8Server:t}=await mp(async()=>{let{createAgent8Server:e}=await import(`./agent8-BxNvAcLA.js`);return{createAgent8Server:e}},[],import.meta.url);return t(e)}var ck=class extends Fe{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=nk.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=Ct(n.resolveScene(this.scene).root)}catch(t){throw this.failedKeys.add(e),t}r.name=lk(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}let i=t.sync;i&&ok(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 lk(e){return e.replace(/[/%]/g,`_`)||`remote`}function uk(){lt(),M(ck)}var dk=80,fk=` `;function pk(e){return`${mk(e,0)}\n`}function mk(e,t){if(typeof e!=`object`||!e)return JSON.stringify(e);let n=hk(e);if(t*2+n.length<=dk)return n;let r=fk.repeat(t+1),i=fk.repeat(t);if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>r+mk(e,t+1)).join(`,
7406
+ `)}\n${i}]`;let a=Object.entries(e);return a.length===0?`{}`:`{\n${a.map(([e,n])=>`${r}${JSON.stringify(e)}: ${mk(n,t+1)}`).join(`,
7407
+ `)}\n${i}}`}function hk(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(hk).join(`, `)}]`;let t=Object.entries(e);return t.length===0?`{}`:`{ ${t.map(([e,t])=>`${JSON.stringify(e)}: ${hk(t)}`).join(`, `)} }`}async function gk(e){if(!e.ok)throw Error(`HTTP ${e.status} — ${await e.text()}`);return e}async function _k(){return await(await gk(await fetch(`/api/meta`))).json()}async function vk(){return await(await gk(await fetch(`/api/scenes`))).json()}async function yk(e){return await(await gk(await fetch(`/api/scenes`,{method:`POST`,body:JSON.stringify({path:e})}))).json()}function bk(e){return e?`/api/scene?file=${encodeURIComponent(e)}`:`/api/scene`}async function xk(e){return await(await gk(await fetch(bk(e)))).json()}async function Sk(e,t){await gk(await fetch(bk(t),{method:`PUT`,body:pk(e)}))}var Ck=localStorage.getItem(`incanto-editor-lang`)??`en`,wk=new Set;function Tk(){return Ck}function Ek(e){Ck=e,localStorage.setItem(`incanto-editor-lang`,e);for(let e of wk)e()}function Dk(e){wk.add(e)}function Ok(e){return e[Ck]}var kk={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`]}},Ak={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 jk(e){let t=kk[Ak[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 Mk(){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 Nk=[{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`]}],Pk=new Set,Fk=null,Ik=null;function Lk(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 Rk(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 zk(e){let t=e.assets.length;for(let n of e.folders.values())t+=zk(n);return t}function Bk(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(Qk(i.type??``)),s.addEventListener(`click`,e=>{e.stopPropagation(),$k(s,i.type??``)}),Fk===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;o.appendChild(Lk(a,r=>{Fk=null,t.renameAssetKey(e,n+r)},()=>{Fk=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(),Fk=e,t.selectAsset(e)}),o.append(s,c),o.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(o)},o=(e,n)=>{let r=Pk.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(Mk());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),Ik===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,Lk(e.name,n=>{Ik=null,t.renameGroup(e.path,i+n)},()=>{Ik=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(),Ik=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${zk(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{Pk.has(e.path)?Pk.delete(e.path):Pk.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=Rk(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function Vk(e,t,n){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(rA(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(qk(`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 Gk(e,t);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(rA(`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(Jk(`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 r=t.selectedAsset;if(r===null)return!1;let i=t.working.assets??{};if(!(r in i))return!1;e.appendChild(rA(`ASSET — ${String(i[r].type??`?`)}`)),e.appendChild(eA(r)),e.appendChild(tA(t,r)),e.appendChild(Hk(t,i,r));let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost danger`,a.textContent=`delete asset`,a.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete i[r],Object.keys(i).length===0&&delete t.working.assets})}),e.appendChild(a),!0}function Hk(e,t,n){let r=t[n],i=document.createElement(`div`);i.className=`asset-editor`;let a=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,o=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,s=Jk(`name`,a,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==a&&e.renameAssetKey(n,o+r)});nA(s.querySelector(`input`)),i.appendChild(s),i.appendChild(Jk(`url`,String(r.url??``),t=>{e.mutate(()=>{r.url=t.trim()})}));let c=document.createElement(`div`);c.className=`muted-note`,c.textContent=`meta (key · value)`,i.appendChild(c);for(let[t,n]of Object.entries(r))t===`type`||t===`url`||i.appendChild(Uk(e,r,t,n));return i.appendChild(Wk(e,r)),i}function Uk(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]=Yk(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 Wk(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]=Yk(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function Gk(e,t){return e.appendChild(rA(`NEW ASSET`)),e.appendChild(Kk(t)),!0}function Kk(e){let t=document.createElement(`div`);t.className=`asset-editor`;let n=document.createElement(`select`);for(let e of Nk){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,n.appendChild(t)}t.appendChild(qk(`type`,n));let r=document.createElement(`input`);r.placeholder=`(optional) characters`,r.className=`mono`,r.value=e.newAssetGroup;let i=`asset-groups-list`;r.setAttribute(`list`,i);let a=document.createElement(`datalist`);a.id=i;let o=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&o.add(t.slice(0,e))}for(let t of e.pendingGroups)o.add(t);for(let e of o){let t=document.createElement(`option`);t.value=e,a.appendChild(t)}t.appendChild(qk(`group`,r)),t.appendChild(a);let s=document.createElement(`input`);s.placeholder=`coin`,s.className=`mono`,nA(s),t.appendChild(qk(`key`,s));let c=document.createElement(`input`);c.placeholder=`/textures/coin.png · https://… · data:…`,c.className=`mono`,t.appendChild(qk(`url`,c));let l=document.createElement(`textarea`);l.rows=2,l.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,t.appendChild(l);let u=document.createElement(`button`);u.type=`button`,u.className=`primary`,u.textContent=`add`,u.addEventListener(`click`,()=>{let t=s.value.trim().replace(/^\$/,``);if(!t)return;let i=r.value.trim().replace(/\/+$/,``),a=i?`${i}/${t}`:t,o=null,u=l.value.trim();if(u)try{o=JSON.parse(u)}catch{l.classList.add(`invalid`);return}else c.value.trim()&&(o={type:n.value,url:c.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 d=document.createElement(`div`);return d.className=`pop-actions`,d.appendChild(u),t.appendChild(d),t}function qk(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 Jk(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),qk(e,r)}function Yk(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 Xk={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`},Zk={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 Qk(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`,Xk[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function $k(e,t){document.querySelector(`.balloon`)?.remove();let n=Zk[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=Ok(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 eA(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 tA(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 nA(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function rA(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 iA=window.parent!==window,aA=new URLSearchParams(window.location.search).get(`parentOrigin`),oA=!1;function sA(e){if(iA){if(!aA){oA||(oA=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,aA)}}var cA={ready(e,t,n){sA({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){sA({type:`incanto-editor:open`,input:e,output:t})},change(e){sA({type:`incanto-editor:change`,dirty:e})},save(e,t,n){sA({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){sA({type:`incanto-editor:error`,message:e})}},lA=[[`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`]],uA=[...lA,[`Other`,e=>lA.every(([,t])=>!t(e))]],dA={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 editor shows and edits these links but the code lives in the game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 에디터는 이 연결을 보여주고 편집하지만 코드는 게임에 있습니다.`}},{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 아바타에 자동 리타게팅됩니다.`}}]},Z=(e,t,...n)=>({type:e,summary:t,body:n}),fA=[{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:[Z(`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 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Z(`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 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Z(`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로 캔버스 위에 올립니다.`}),Z(`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는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Z(`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로 작은 캡션을 붙입니다.`}),Z(`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) 시그널을 냅니다.`}),Z(`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()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Z(`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를 확인하세요.`}),Z(`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:[Z(`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로 서브트리 표시를 제어합니다.`}),Z(`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로 정해집니다.`}),Z(`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가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Z(`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) 칸의 좌상단이 노드 원점에 걸립니다.`}),Z(`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)를 발산합니다.`}),Z(`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인 카메라가 실제 시점이 됩니다.`}),Z(`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를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`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).`}),Z(`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:[Z(`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:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Z(`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를 권합니다.`}),Z(`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)는 길을 막지 않으면서 트리거를 발사합니다.`}),Z(`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")로 거릅니다.`}),Z(`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는 의도 그대로의 숫자입니다.`}),Z(`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:[Z(`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은 축별. 자식이 상속합니다.`}),Z(`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.`}),Z(`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 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Z(`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).',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨).'}),Z(`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로 색·투명도.`}),Z(`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 연결).`}),Z(`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(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Z(`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)으로 정확한 렌더 결과를 미리 보세요.`}),Z(`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와 함께 쓰세요.`}),Z(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Z(`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] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Z(`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'}를 쓰세요.`}),Z(`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를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Z(`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.`,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가 배치를 재현 가능하게 합니다.`}),Z(`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.`,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.`}),Z(`Tree3D`,{en:`Procedural ez-tree groves — branchy trunks, textured leaves.`,ko:`프로시저럴 ez-tree 나무 — 가지 달린 줄기와 텍스처 잎까지.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Z(`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:[Z(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry.`,ko:`바닥·벽·레벨 지형.`}),Z(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Z(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Z(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Z(`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 같은 의도 수준의 숫자만 만집니다.`}),Z(`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 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Z(`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면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Z(`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:[Z(`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를 발산합니다.`})]}],pA=`overview`,mA=null;function hA(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),vA()}function gA(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function _A(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&gA()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,gA))}function vA(){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${pA===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{pA=t,mA=null,vA()}),e.appendChild(r)};n(`overview`,Ok({en:`Overview`,ko:`개요`}));for(let e of fA)n(e.id,Ok(e.label));if(t.textContent=``,pA===`overview`){yA(t);return}let r=fA.find(e=>e.id===pA);r&&bA(t,r)}function yA(e){let t=document.createElement(`h2`);t.textContent=Ok(dA.title),e.appendChild(t);for(let t of dA.sections){let n=document.createElement(`h3`);n.textContent=Ok(t.heading);let r=document.createElement(`p`);r.textContent=Ok(t.text),e.append(n,r)}}function bA(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=Ok(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${mA===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(jk(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=Ok(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{mA=mA===n.type?null:n.type,vA()}),t.appendChild(r),mA===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=Ok(t),e.appendChild(n)}e.appendChild(xA(n.type)),t.appendChild(e)}e.appendChild(t)}}function xA(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[Ok({en:`prop`,ko:`prop`}),Ok({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ge(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 Q(e){return Math.round(e*100)/100}function SA(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 CA(e,t,n,r,i,a){let o=Q(r.range(i[0],i[1])),s=Q(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,Q(o*s*.6),n],rotation:[0,r.int(0,359),0],scale:[o,Q(o*s),Q(o*r.range(.8,1.1))],material:{color:a??wA(r),roughness:1},castShadow:!0}}}function wA(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function TA(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(e*.8),Q(e*1.5),Q(e*.6)],intensity:1,castShadow:!0,shadowArea:Q(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-e*.8),Q(e*.8),Q(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function EA(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function DA(e,t,n){return Math.min(Math.max(e,t),n)}var OA=[`boxes`,`ruins`,`garden`],kA=.5,AA=.1,jA=2,MA={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 NA(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!OA.includes(o))throw new y(`BAD_FORMAT`,`generateArena theme must be one of [${OA.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...OA]});let s=MA[o],c=new b(t),l=[SA(`Floor`,[n,AA,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+kA*2,i,kA],f=[kA,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(SA(`Wall1`,d,[0,u,-(r+kA)/2],p),SA(`Wall2`,d,[0,u,(r+kA)/2],p),SA(`Wall3`,f,[-(n+kA)/2,u,0],p),SA(`Wall4`,f,[(n+kA)/2,u,0],p)),o===`ruins`?l.push(...FA(c,s,n,r,i,a)):l.push(...PA(c,s,n,r,i,a,o)),o===`garden`&&l.push(...IA(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[Q(m*.8),Q(m*1.5),Q(m*.6)],intensity:1,castShadow:!0,shadowArea:Q(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[Q(-m*.8),Q(m*.8),Q(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,Q(i+2),0],intensity:.5,color:`#fff3d6`,range:Q(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function PA(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=[Q(e.range(.8,2.6)),Q(e.range(.8,Math.max(1.2,i*.8))),Q(e.range(.8,2.6))],l=Q(e.range(-(n/2-jA),n/2-jA)),u=Q(e.range(-(r/2-jA),r/2-jA));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=Q(l/t*(c+1.5+e.range(0,2))),u=Q(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(SA(`Obstacle${o}`,a,[l,Q(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function FA(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-jA*2,u=r-jA*2,d=0;for(let n=0;n<s&&d<a;n++){let r=Q(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=Q((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=Q(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=Q(e.range(.8,1.2));o.push(SA(`Obstacle${d}`,[u,s,u],[a,Q(s/2),Q(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function IA(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=Q(e.range(-a,a)),s=Q(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=Q(o/c*(i+r/2+.5)),s=Q(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=Q(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=Q(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:[Q(i*2),Q(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var LA=32,RA=[4,8],zA=`#332f3a`,BA=`#6b6357`;function VA(e){let{seed:t,rooms:n=5}=e,[r,i]=EA(e.size,[960,720]),a=Math.max(8,Math.floor(r/LA)),o=Math.max(8,Math.floor(i/LA)),s=new b(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(RA[0],RA[1]),t=s.int(RA[0],RA[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=>HA(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]=UA(c[e-1]),[r,i]=UA(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*LA)/2,m=-(o*LA)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*LA,m+(t.y+t.h/2)*LA],size:[t.w*LA,t.h*LA],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,zA));for(let e of d)g.push(h(e.name,e.rect,zA));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*LA,LA];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*LA,m+(e+.5)*LA],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:BA}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function HA(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 UA(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var WA=[[0,-1],[1,0],[0,1],[-1,0]];function GA(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 WA){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 KA=[`stone`,`hedge`,`canyon`],qA=.1,JA=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,YA=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,XA={stone:{wall:{color:`#e8e2d8`,map:`${JA}/blocks.png`,normalMap:`${JA}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${YA}/stone.png`,normalMap:`${YA}/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:`${YA}/grass.png`,normalMap:`${YA}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${YA}/grass.png`,normalMap:`${YA}/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:`${YA}/stone.png`,normalMap:`${YA}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${YA}/sand.png`,normalMap:`${YA}/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 ZA(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[Q(t/e.tile),Q(n/e.tile)]}}var QA=10;function $A(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!KA.includes(o))throw new y(`BAD_FORMAT`,`generateMaze theme must be one of [${KA.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...KA]});let s=XA[o],c=new b(t),l=GA(c,n,r),u=2*n+1,d=2*r+1,f=Q(u*i),p=Q(d*i),m=(e,t)=>[Q((e+.5)*i-f/2),Q((t+.5)*i-p/2)],h=[SA(`Floor`,[f,qA,p],[0,-.1/2,0],{material:ZA(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=Q(n*i);h.push(SA(`Wall${_}`,[r,a,i],[Q((t+n/2)*i-f/2),Q(a/2),Q((e+.5)*i-p/2)],{material:ZA(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...ej(g,i,a,f,p,s.cap)),h.push(...tj(c,l,i,a,m,s)),o===`hedge`?(h.push(...aj(c,g,i,a,m)),h.push(...oj(c,l,i,m,n,r))):o===`canyon`&&h.push(...sj(c,g,i,a,m)),h.push(...rj(l,i,a,m,s)),h.push(...TA(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,Q((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function ej(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[Q(e.run*t+.16),.12,Q(t+.16)],position:[Q((e.gx+e.run/2)*t-r/2),Q(n+.06),Q((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function tj(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(QA,o.length),l=[],u=new Set,d=Q(n*1.2),f=Q(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(nj(`Pillar${t}`,c,p,d,f,a))}return l}function nj(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,Q(i/2),n],material:{...ZA(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function rj(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=Q(t*1.1),c=Q(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 nj(`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:[Q(t*.96),.04,Q(t*.96)],position:[a,.02,o],material:{...ZA(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var ij=10;function aj(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,ij).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:[Q(t.run*n*.92),Q(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[Q((s+c)/2),r,o]}}})}function oj(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=Q(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 sj(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=CA(s,c,l,e,[.3,Q(n*.35)],`#8f7355`),d=u.props?.position;d[1]=Q(d[1]+r),a.push(u)}return a}var cj=`#23222b`,lj=`#5f6672`;function uj(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=GA(new b(t),n,r),o=2*n+1,s=2*r+1,c=Q(o*i),l=Q(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:cj}}],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=[Q(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[Q((t+n/2)*i-c/2),Q((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:lj}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var dj=16,fj=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function pj(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 b(t),c=[],l=Q(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(mj(e,u,d,l,s.pick(fj))),e!==n);e++){let e=Q(s.range(r[0],r[1])),t=Q(s.range(i[0],i[1]));u=Q(u+l/2+t+e/2),d=Q(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function mj(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,dj]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,dj],color:i}}]}}var hj=[3,5],gj=3,_j={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function vj(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=EA(e.area,[60,60]),o=new b(t),s=[];for(let e=1;e<=n;e++){let t=o.int(hj[0],hj[1]),n=[];for(let e=1;e<=t;e++){let r=Q(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[Q((e-(t+1)/2)*o.range(1,1.6)),Q(o.range(-.3,.3)),Q(o.range(-.6,.6))],scale:[Q(r*o.range(1.1,1.6)),Q(r*.55),r],material:_j}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[Q(o.range(-i/2,i/2)),Q(r+o.range(-3,gj)),Q(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,children:s}}var yj=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],bj=128,xj=20,Sj=.8,Cj=.12,wj={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 Tj(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=wj[n];if(!a)throw new y(`BAD_FORMAT`,`generateTerrain theme must be one of [${yj.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...yj]});let o=e.maxHeight||a.maxHeight,s=new b(t),c=n===`island`,l=e=>Ry({width:r,depth:r,segsX:bj,segsZ:bj,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:c}),u=l(o);if(c)for(let e=0;e<3;e++){let e=Dj(u)-xj,t=u.maxHeight-u.minHeight,n=u.minHeight+Cj*t;if(e+Sj<=n)break;let r=xj-Sj,i=Dj(u)-u.minHeight-Cj*t;o=Q(o*Math.min(r/i*.95,.9)),u=l(o)}let d=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:o,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail}}}]}],f=n===`wetland`;if(c)d.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,Ej(u),0],opacity:1}});else if(f){let e=u.maxHeight-u.minHeight||1,t=Q(u.minHeight+.22*e);d.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=Q(u.minHeight+.1*(u.maxHeight-u.minHeight));d.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return d.push(...Uj(n,s,u,r)),c&&d.push(vj({seed:s.int(1,1e9),count:6,area:r,altitude:Math.round(u.maxHeight+12)})),d.push(...TA(r).map((e,t)=>Wj(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:d}}function Ej(e){let t=Dj(e)-xj,n=e.minHeight+Cj*(e.maxHeight-e.minHeight);return Q(Math.max(Math.min(t+Sj,n),t+.55))}function Dj(e){let t=-1/0,n=e.width/2,r=e.depth/2;for(let i=0;i<=bj;i++){let a=-n+i/bj*e.width,o=-r+i/bj*e.depth;t=Math.max(t,e.baseHeight(a,-r),e.baseHeight(a,r),e.baseHeight(-n,o),e.baseHeight(n,o))}return t}function Oj(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=Q(e.range(-r,r)),s=Q(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 kj=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],Aj=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],jj={canopy:`#9aa052`,trunk:`#8a6a44`},Mj={canopy:`#39513f`,trunk:`#5a5650`};function Nj(e,t){return e===`conifer`?t.pick(kj):e===`broadleaf`?t.pick(Aj):null}function Pj(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=Nj(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:Q(n.range(a[0],a[1])),position:[t.x,Q(t.y-o),t.z],...s}}}function Fj(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,Q(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function Ij(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,Q(t.y+.02),t.z]}}}function Lj(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,Q(t.y+.02),t.z]}}}function Rj(e,t,n,r){return e.map((e,i)=>{let a=CA(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=Q(o[1]+e.y),a})}function zj(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 Bj(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 Vj(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 Hj=[`#6f5b41`,`#7a644a`,`#665439`];function Uj(e,t,n,r){let i=[];switch(e){case`island`:{let e=Oj(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=Oj(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`conifer`)));let r=Oj(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...Rj(r,t,[.6,1.8]));break}case`plains`:{let e=Oj(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`broadleaf`)));let r=Oj(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...Rj(r,t,[.4,1.2]));break}case`desert`:{let e=Oj(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`dead`)));let r=Oj(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...Rj(r,t,[.5,1.6]));break}case`meadow`:{let e=Q(r*.09),a=Oj(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>Fj(`Carpet${r+1}`,n,t,e,30)));let o=Q(r*.07),s=Oj(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Lj(`Flowers${n+1}`,e,t,o,`sparse`)));let c=Oj(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>Pj(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=Oj(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...Rj(l,t,[.3,.9]));break}case`forest`:{let e=Q(r*.12),a=r/2-8,o=tt(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=Oj(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)=>Pj(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(Pj(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=Oj(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>Pj(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=Oj(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>Pj(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=Oj(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>Pj(`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=Q(DA(e.x+Math.cos(o)*s,-a,a)),u=Q(DA(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,Q(n.heightAt(l,u)+.02),u]}}))});let m=Q(r*.08),h=Oj(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>Fj(`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=Q(DA(r.x+Math.cos(o)*s,-a,a)),l=Q(DA(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:Q(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,Q(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),Q(t.range(81,97))]}})}Oj(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=Q(t.range(.16,.28)),a=Q(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,Q(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(Hj),roughness:1},castShadow:!0}})});let _=Oj(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...Rj(_,t,[.3,1],zj));let v=Q(e*.75),y=Oj(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-Q(v/Math.SQRT2)});i.push(...y.map((e,n)=>Fj(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=Q(e*.45),x=Oj(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-Q(b/Math.SQRT2)});i.push(...x.map((e,n)=>Lj(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=Oj(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:jj})));let a=Q(r*.09),o=Oj(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>Fj(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=Oj(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...Rj(s,t,[.4,1.4]));let c=Oj(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>Pj(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=Oj(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:Mj})));let r=Oj(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...Rj(r,t,[.5,1.8],Bj));break}case`wetland`:{let e=Q(r*.08),a=Oj(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>Ij(`Reeds${r+1}`,n,t,e,4)));let o=Q(r*.08),s=Oj(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>Fj(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=Oj(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>Pj(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=Oj(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>Pj(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=Oj(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...Rj(u,t,[.3,1],zj));break}case`volcanic`:{let e=Oj(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>Pj(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=Oj(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...Rj(r,t,[.4,1.8],Vj)),Oj(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,Q(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,Q(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 Wj(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var Gj={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:[...OA]},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:[...yj]},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:[...KA]},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}}}},Kj={arena:NA,terrain:Tj,maze:$A,maze2d:uj,dungeon2d:VA,platforms2d:pj};function qj(e,t){let n=Kj[e];if(!n){let t=Object.keys(Kj);throw new y(`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 Jj(e){return Object.entries(Gj).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function Yj(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 Xj(){return Math.floor(Math.random()*1e6)}var Zj=[],Qj=new Map,$j=null;function eM(e){let t=document.querySelector(`#generate`);t&&(rM(e),t.removeAttribute(`hidden`))}function tM(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function nM(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&tM()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,tM),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,tM),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>iM(e)))}function rM(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`;Zj=Jj(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=Ok({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=aM(Ok({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of Zj){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=aM(`seed`);$j=document.createElement(`input`),$j.type=`number`,$j.step=`1`,$j.value=String(Xj());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=Ok({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{$j&&($j.value=String(Xj()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append($j,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=Zj.find(e=>e.name===o.value)??Zj[0];if(e){s.textContent=e.meta.description,c.textContent=``,Qj=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=aM(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??``}`);Qj.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function iM(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=Zj.find(e=>e.name===n?.value);if(!r||!$j)return;let i={seed:Yj({type:`number`,default:Xj(),min:0},$j.value)};for(let[e,t]of Qj){let n=r.meta.params[e];n&&(i[e]=Yj(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=qj(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=Ok({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),$j&&($j.value=String(Xj())),tM()}function aM(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var oM={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';
7408
7408
 
7409
7409
  export class MyBehavior extends Behavior {
7410
7410
  static props = { speed: { default: 100 } };
@@ -7414,4 +7414,4 @@ export class MyBehavior extends Behavior {
7414
7414
  update(dt: number): void {}
7415
7415
  }
7416
7416
  registerBehavior('MyBehavior', MyBehavior); // before loadScene()
7417
- `}},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] }`}},$j=null;function eM(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=Qj[r.dataset.help??``];if(!i)return;if(!e.hidden&&$j===r){e.hidden=!0;return}$j=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=bk(i.title);let o=document.createElement(`div`);if(o.textContent=bk(i.body),e.append(a,o),i.example){let t=document.createElement(`pre`);t.textContent=i.example,e.appendChild(t)}if(i.copy){let t=document.createElement(`div`);t.className=`pop-actions`;let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`⧉ ${i.copy.label}`,n.addEventListener(`click`,()=>{navigator.clipboard.writeText(i.copy?.text??``),n.textContent=`✓ copied`}),t.appendChild(n),e.appendChild(t)}e.hidden=!1;let s=r.getBoundingClientRect();e.style.left=`${Math.max(8,Math.min(innerWidth-300-8,s.left-300+20))}px`,e.style.top=`${Math.min(innerHeight-60,s.bottom+8)}px`})}function tM(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 nM=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 rM(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function iM(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 aM(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 oM=nM;function sM(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function cM(e,t,n){if(e.textContent=``,t.selection===null){uM(e,t,n);return}let r=t.nodeAt(t.selection);r&&gM(e,t,r,n)}var lM=[`input`,`multiplayer`];function uM(e,t,n){e.appendChild(VM(`scene`)),e.appendChild(GM(`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(UM(`dimension`,r)),e.appendChild(VM(`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(qM(`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(VM(`environment`)),dM(e,t),e.appendChild(VM(`constants`)),FM(e,t,n),e.appendChild(VM(`advanced`));for(let n of lM)e.appendChild(YM(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function dM(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(fM(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(fM(`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(KM(`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(UM(`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(UM(`pixel ratio`,s))}function fM(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),UM(e,r)}function pM(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(UM(`enabled`,l)),a){n.appendChild(fM(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(KM(`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(UM(`caustics`,e))}return n}function mM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.textContent=`material`,n.appendChild(r);let i=t.props?.material??{},a=(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)};n.appendChild(fM(`color`,String(i.color??``),e=>a(`color`,e))),n.appendChild(hM(`roughness`,Number(i.roughness??1),e=>a(`roughness`,e))),n.appendChild(hM(`metalness`,Number(i.metalness??0),e=>a(`metalness`,e))),n.appendChild(fM(`emissive`,String(i.emissive??``),e=>a(`emissive`,e))),n.appendChild(hM(`emissive power`,Number(i.emissiveIntensity??1),e=>a(`emissiveIntensity`,e===1?void 0:e),2)),n.appendChild(hM(`opacity`,Number(i.opacity??1),e=>a(`opacity`,e===1?void 0:e))),n.appendChild(hM(`clearcoat`,Number(i.clearcoat??0),e=>a(`clearcoat`,e===0?void 0:e))),n.appendChild(hM(`clearcoat rough`,Number(i.clearcoatRoughness??0),e=>a(`clearcoatRoughness`,e===0?void 0:e))),n.appendChild(hM(`reflection`,Number(i.envMapIntensity??1),e=>a(`envMapIntensity`,e===1?void 0:e),3));let o=document.createElement(`input`);o.type=`checkbox`,o.checked=i.wireframe===!0,o.addEventListener(`change`,()=>a(`wireframe`,o.checked||void 0)),n.appendChild(UM(`wireframe`,o));let s=document.createElement(`input`);s.type=`checkbox`,s.checked=i.flatShading===!0,s.addEventListener(`change`,()=>a(`flatShading`,s.checked||void 0)),n.appendChild(UM(`flatShading`,s));let c=document.createElement(`input`);c.type=`checkbox`,c.checked=i.depthTest===!1,c.addEventListener(`change`,()=>{a(`depthTest`,c.checked?!1:void 0),a(`depthWrite`,c.checked?!1:void 0)}),n.appendChild(UM(`draw on top (decal)`,c)),n.appendChild(EM(`map (texture)`,String(i.map??``),DM(e=>sM(e)&&!e.name.includes(`normal`)&&!e.name.includes(`roughness`)),e=>a(`map`,e.trim()),{placeholder:`built-in or custom URL`})),n.appendChild(EM(`normal map`,String(i.normalMap??``),DM(e=>sM(e)&&e.name.includes(`normal`)),e=>a(`normalMap`,e.trim()),{placeholder:`built-in or custom URL`}));let l=!!(i.map||i.normalMap),u=Array.isArray(i.repeat)?i.repeat:[1,1],d=qM(`repeat [u,v]`,[u[0]??1,u[1]??1],e=>{let[t,n]=e;!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1||!t&&!n?a(`repeat`,void 0):a(`repeat`,[t,n])});return d.title=l?`Texture tiling across the mesh UVs.`:`Only takes effect with a map/normal map set (engine validates).`,n.appendChild(d),n}function hM(e,t,n,r=1){let i=document.createElement(`div`);i.className=`slider-row`;let a=document.createElement(`input`);a.type=`range`,a.min=`0`,a.max=String(r),a.step=`0.05`,a.value=String(Number.isFinite(t)?t:0);let o=document.createElement(`input`);return o.type=`number`,o.step=`0.05`,o.min=`0`,o.max=String(r),o.value=a.value,a.addEventListener(`input`,()=>{o.value=a.value}),a.addEventListener(`change`,()=>n(Number(a.value))),o.addEventListener(`change`,()=>{a.value=o.value,n(Number(o.value))}),i.append(a,o),UM(e,i)}function gM(e,t,n,r){if(e.appendChild(VM(n.type??`instance`)),e.appendChild(_M(n)),e.appendChild(GM(`name`,n.name??``,e=>{e.trim()!==``&&t.mutate(()=>{n.name=e.trim()})})),n.type===`TileMap2D`&&r?.paint&&e.appendChild(JM(n,r.paint)),n.type){let i;try{i=_e(n.type)}catch{i={}}for(let[a,o]of Object.entries(i))if(a===`collider`)e.appendChild(xM(t,n,o.default));else if(a===`material`)e.appendChild(mM(t,n));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(wM(`model`,String(n.props?.model??``),r.modelRefs(),e=>SM(t,n,`model`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(wM(`animation`,String(n.props?.animation??``),r.animationsForSelection(),e=>SM(t,n,`animation`,e,``)));else if(n.type===`Tree3D`&&a===`leafTexture`)e.appendChild(EM(`leaf texture`,String(n.props?.leafTexture??``),DM(e=>e.name.startsWith(`leaves_`)),e=>SM(t,n,`leafTexture`,e.trim(),``),{placeholder:`default (per-type) or URL`}));else if(n.type===`Terrain3D`&&a===`textureBase`)e.appendChild(EM(`texture base`,String(n.props?.textureBase??o.default??``),kM,e=>SM(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(AM(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(EM(`src (audio file)`,String(n.props?.src??``),OM(),e=>SM(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."})):n.type===`Flowers3D`&&a===`varieties`?e.appendChild(jM(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(pM(t,n)):e.appendChild(LM(t,n,a,o.default,o.options))}e.appendChild(VM(`structure`)),e.appendChild(vM(t,n)),e.appendChild(yM(t,n)),e.appendChild(bM(t,n))}function _M(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 vM(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,tM(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(HM(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 yM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,tM(`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(GM(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(YM(`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 bM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,tM(`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(UM(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(HM(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(KM(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function xM(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,tM(`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(UM(`shape`,l)),a.shape===`rect`||a.shape===`box`?r.appendChild(qM(`size`,a.size??(s?[1,1,1]:[32,32]),e=>o({...a,size:e}))):a.shape===`circle`||a.shape===`sphere`?r.appendChild(KM(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(KM(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(KM(`height`,a.height??16,e=>o({...a,height:e})))),a.shape&&r.appendChild(qM(`offset`,a.offset??(s?[0,0,0]:[0,0]),e=>o({...a,offset:e}))),r}function SM(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 CM=0;function wM(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${CM++}`;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=UM(e,i);return s.appendChild(o),s}var TM=0;function EM(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`);l.className=`asset-control`,l.append(s,c),a.appendChild(l);let u=document.createElement(`div`);u.className=`asset-panel`,u.hidden=!0;let d=document.createElement(`input`);d.type=`text`,d.className=`asset-search`,d.placeholder=`search ${n.length} built-in${n.length===1?``:`s`}…`;let f=document.createElement(`div`);f.className=`asset-options`,u.append(d,f),a.appendChild(u);let p=e=>{f.textContent=``;let t=e.trim().toLowerCase(),i=n.filter(e=>t===``||e.label.toLowerCase().includes(t)||(e.hint?.toLowerCase().includes(t)??!1)||e.value.toLowerCase().includes(t));if(i.length===0){let e=document.createElement(`div`);e.className=`asset-empty`,e.textContent=`no match — type a custom URL above`,f.appendChild(e);return}for(let e of i){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-option`;let n=document.createElement(`strong`);if(n.textContent=e.label,t.appendChild(n),e.hint){let n=document.createElement(`small`);n.textContent=e.hint,t.appendChild(n)}t.addEventListener(`click`,()=>{s.value=e.value,u.hidden=!0,r(e.value)}),f.appendChild(t)}};if(c.addEventListener(`click`,()=>{u.hidden=!u.hidden,u.hidden||(p(d.value),d.focus())}),d.addEventListener(`input`,()=>p(d.value)),d.addEventListener(`keydown`,e=>{e.key===`Escape`&&(u.hidden=!0)}),i.note){let e=document.createElement(`div`);e.className=`muted-note asset-note`,e.textContent=i.note,a.appendChild(e)}return s.id=`asset-input-${TM++}`,a.htmlFor=s.id,a}function DM(e){return oM.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description.slice(0,70)}`}))}function OM(){return oM.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description.slice(0,70)}`}))}var kM=[{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 AM(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=oM.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 EM(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)}SM(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}SM(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."})}function jM(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=Lx.filter(e=>i.has(e));SM(e,t,`varieties`,n.length===0||n.length===Lx.length?[]:n,[])};for(let e of Lx){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 Lx)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 MM=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function NM(e,t){let n=0,r=e=>{if(ft(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 PM(e,t,n){let r=e=>{if(ft(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 FM(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&&PM(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=NM(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(IM(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 MM){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,(MM.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function IM(e,t,n){let r=de(t);if(r===`number`)return KM(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)),UM(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?qM(e,t,e=>n(e)):r===`string`?GM(e,String(t),e=>n(e)):YM(e,t,e=>n(e??null),JSON.stringify(t))}function LM(e,t,n,r,i){let a=t.props?.[n]??r,o=de(r),s=o===`number`||o===`boolean`||o===`string`||o===`array`,c=i=>{let a=ft(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&&s&&!a?{path:e.selection,key:n,value:i}:void 0)},l=RM(e,o,r);if(ft(a))return zM(n,a[`@const`],l,c,r);let u=e=>l.length>0?BM(e,l,c):e;if(o===`number`)return u(KM(n,a,e=>c(e),()=>c(r)));if(o===`boolean`){let e=document.createElement(`input`);return e.type=`checkbox`,e.checked=a===!0,e.addEventListener(`change`,()=>c(e.checked)),u(UM(n,e))}return o===`string`?i&&i.length>0?u(WM(n,String(a??``),i,e=>c(e))):u(GM(n,String(a??``),e=>c(e))):o===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?u(qM(n,a??r,e=>c(e))):YM(n,a===r?void 0:a,e=>{c(e===void 0?r:e)},JSON.stringify(r))}function RM(e,t,n){let r=e.working.constants??{};return Object.keys(r).filter(e=>{let i=r[e];return de(i)===t?t===`array`&&Array.isArray(n)&&Array.isArray(i)?i.length===n.length:!0:!1})}function zM(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=UM(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function BM(e,t,n){let r=document.createElement(`select`);r.className=`const-picker`,r.title=`Bind to a named constant`;let i=document.createElement(`option`);i.value=``,i.textContent=`🔗`,r.appendChild(i);for(let e of t){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}return r.value=``,r.addEventListener(`change`,()=>{r.value&&n({"@const":r.value})}),e.appendChild(r),e}function VM(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(tM(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function HM(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 UM(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 WM(e,t,n,r){let i=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),i.appendChild(n)}return i.addEventListener(`change`,()=>r(i.value)),UM(e,i)}function GM(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),UM(e,r)}function KM(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)}),UM(e,i)}function qM(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)}),UM(e,r)}function JM(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 aM(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 YM(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=UM(e,i);return a.className=`field wide`,a}var XM=class{working;selection=[];extra=[];validator=null;selectedAsset=null;selectedGroup=null;pendingGroups=new Set;pendingLivePatch=null;addingAsset=!1;addingGroup=!1;newAssetGroup=``;newGroupParent=``;startAddingAsset(){this.addingAsset=!0,this.addingGroup=!1,this.newAssetGroup=this.selectedGroup??``,this.clearFocus()}startAddingGroup(){this.addingGroup=!0,this.addingAsset=!1,this.newGroupParent=this.selectedGroup??``,this.clearFocus()}cancelAddForms(){this.addingAsset=!1,this.addingGroup=!1}onError=null;original;undoStack=[];listeners=new Set;constructor(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&ZM(this.working.root)}get dirty(){return JSON.stringify(this.working)!==this.original}get canUndo(){return this.undoStack.length>0}nodeAt(e){if(e===null)return null;let t=this.working.root;for(let n of e)t=t?.children?.[n];return t??null}parentOf(e){return e.length===0?null:this.nodeAt(e.slice(0,-1))}mutate(e,t){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?r(i):(this.undoStack.push(t),this.undoStack.length>100&&this.undoStack.shift(),this.emit(),n)}moveNode(e,t,n){return this.moveNodes([e],t,n)?.[0]??null}moveNodes(e,t,n){let r=nN(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)iN(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=rN(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=oN(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=aN(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=oN(n,t.name??`Node`),QM(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=nN(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)iN(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 QM(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=oN(n,r.name??`Node`),QM(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=nN(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=nN(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&&$M(this.working,a,i);for(let e of i)iN(r,e);return!0})===!0}reset(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&ZM(this.working.root),this.undoStack=[],this.selection=[],this.emit()}markSaved(){this.original=JSON.stringify(this.working),this.emit()}emitChange(){this.emit()}clearFocus(){this.selection=null,this.extra=[],this.selectedAsset=null,this.selectedGroup=null,this.emit()}selectAsset(e){this.selectedAsset=e,e!==null&&(this.cancelAddForms(),this.selectedGroup=null,this.selection=null,this.extra=[]),this.emit()}selectGroup(e){this.selectedGroup=e,e!==null&&(this.cancelAddForms(),this.selectedAsset=null,this.selection=null,this.extra=[]),this.emit()}assetMap(){return this.working.assets??{}}groupCount(e){return Object.keys(this.assetMap()).filter(t=>t.startsWith(`${e}/`)).length}addGroup(e){this.pendingGroups.add(e),this.selectGroup(e)}renameGroup(e,t){if(!t||t===e)return!1;let n=this.assetMap(),r=Object.keys(n).filter(t=>t.startsWith(`${e}/`));return this.pendingGroups.delete(e)&&this.pendingGroups.add(t),this.selectedGroup=t,this.mutate(()=>{for(let i of r){let r=`${t}/${i.slice(e.length+1)}`;n[r]=n[i],delete n[i],eN(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],eN(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(tN)}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 ZM(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Ft());for(let t of e.children??[])ZM(t)}function QM(e){e.uid=Ft();for(let t of e.children??[])QM(t)}function $M(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):$M(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]:$M(i,t,n))}}function eN(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:eN(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:eN(i,t,n)}function tN(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 nN(e){let t=[...e].sort(tN),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 rN(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=rN(n,t);if(e)return e}return null}function iN(e,t){let n=rN(e,t);n?.parent.children?.splice(n.index,1)}function aN(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=aN(r,t);if(e)return[n,...e]}return null}function oN(e,t){let n=new Set((e.children??[]).map(e=>e.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}${r}`);)r+=1;return`${t}${r}`}var sN=new Map(iA.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),cN=new Set,lN=null;function uN(e){lN=e}var dN=null,fN=null,pN=null;function mN(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 hN(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}gN(r,t.selection),e.appendChild(_N(r,[],t,``))}function gN(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),cN.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function _N(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=cN.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&&pN!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(wk()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?cN.delete(i):cN.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${mN(e.type)}`,u.appendChild(Ck(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),vN(u,e.type??`instance`)}),c.append(l,u),pN===i){let t=document.createElement(`input`);t.className=`rename-input`,t.value=e.name??``;let r=()=>{pN=null;let r=t.value.trim();r&&r!==e.name?n.mutate(()=>{e.name=r}):n.select(n.selection)};t.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&r(),e.key===`Escape`&&(pN=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])t.addEventListener(e,e=>e.stopPropagation());t.addEventListener(`blur`,r),c.appendChild(t),queueMicrotask(()=>{t.focus(),t.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),pN=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?cN.delete(i):cN.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),yN(e.clientX,e.clientY,n,t,i)}),ON(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(_N(e,[...t,a],n,i))}),s.appendChild(r)}return s}function vN(e,t){wN();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=sN.get(t);if(i){let e=document.createElement(`span`);e.textContent=bk(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`,TN(n)}function yN(e,t,n,r,i){wN();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`,()=>{wN(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`rename`,o?()=>{pN=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(bN()),c(`cut`,r.length>0?()=>xN(n,!0):null),c(`copy`,r.length>0?()=>xN(n,!1):null),c(`paste as child${fN?` (${fN.nodes.length})`:``}`,fN?()=>SN(n,r):null),s.appendChild(bN()),c(`delete`,r.length>0?()=>(lN??(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`,TN(s)}function bN(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function xN(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);fN={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function SN(e,t){if(fN){for(let n of fN.nodes)e.insertNode(n,t);if(fN.cut){let t=e.working.root,n=fN.cut.map(e=>CN(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),fN={nodes:fN.nodes,cut:null}}}}function CN(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=CN(r,t);if(e)return[n,...e]}return null}function wN(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function TN(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 EN(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function DN(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function ON(e,t,n){e.addEventListener(`dragstart`,r=>{dN=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{dN=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!dN||dN.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),DN(e);let r=t.length===0?`into`:EN(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>DN(e)),e.addEventListener(`drop`,r=>{if(DN(e),!dN)return;r.preventDefault();let i=t.length===0?`into`:EN(r,e),a=n.moveNodes(dN,t,i);dN=null,a?.[0]&&n.select(a[0])})}var kN={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function AN(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 jN(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 MN(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 NN(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function PN(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function FN(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 IN(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=kN[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 LN(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 RN=class{engine;editCanvas;overlay;playCanvas;cb;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;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 je({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.engine.start(),this.engine.updated.connect(()=>this.drawOverlay()),window.addEventListener(`keydown`,e=>{e.key===`Shift`&&(this.shiftHeld=!0)}),window.addEventListener(`keyup`,e=>{e.key===`Shift`&&(this.shiftHeld=!1)}),this.bindPointer()}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);delete t.connections,$N(t.root),nP(t),n=St(t)}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 sm({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new IO({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=ZN(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 delete t.connections,$N(t.root),nP(t),St(t),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=QN(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;showColliders=!0;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=XN(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:kN.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:kN.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition(GN);let r=this.renderer3d.screenFromWorld(GN.x,GN.y,GN.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(GN.x+t[0]*o,GN.y+t[1]*o,GN.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:kN[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=XN(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(GN);let n={x:GN.x,y:GN.y,z:GN.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 V(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new V(r[0],r[1],r[2]).sub(a).normalize(),s=new V().crossVectors(o,VN).normalize();return{pos:a,right:s,up:new V().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 Yb&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(HN),UN.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(WN));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[HN.x+UN.x*e,HN.y+UN.y*e,HN.z+UN.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-UN.x,-UN.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-UN.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 V(1,0,0)],[`y`,new V(0,1,0)],[`z`,new V(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 $C||t instanceof zp||t instanceof nw||t instanceof tD||t instanceof wC)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof $C?t.availableAnimations():[]}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.showColliders&&this.drawColliders3D(e),this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&LN(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.showColliders)for(let[t]of this.pathOf){let n=t.collider;n&&typeof n==`object`&&`shape`in n&&this.drawCollider(e,t,n)}if(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&&LN(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&IN(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&MN(e,t,this.gizmoActive,this.gizmoMode===`scale`)}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)}}drawColliders3D(e){let t=this.renderer3d;if(!t)return;e.save(),e.strokeStyle=zN,e.lineWidth=1.5;let n=(e,n,r)=>t.screenFromWorld(e,n,r),r=(t,r=!1)=>{e.beginPath();let i=!1;for(let[r,a,o]of t){let t=n(r,a,o);if(t.behind){i=!1;continue}i?e.lineTo(t.x,t.y):e.moveTo(t.x,t.y),i=!0}r&&e.closePath(),e.stroke()},i=(e,t,n,i,a)=>{let o=[];for(let r=0;r<=32;r++){let s=r/32*Math.PI*2,c=Math.cos(s)*i,l=Math.sin(s)*i;a===`xz`?o.push([e+c,t,n+l]):a===`xy`?o.push([e+c,t+l,n]):o.push([e,t+c,n+l])}r(o)};for(let[e]of this.pathOf){let t=e.collider,n=e._object3D;if(!t||typeof t!=`object`||!(`shape`in t)||!n)continue;n.getWorldPosition(GN);let a=t.offset??[0,0,0],o=GN.x+(a[0]??0),s=GN.y+(a[1]??0),c=GN.z+(a[2]??0);if(t.shape===`box`){let e=t.size??[1,1,1],n=(e[0]??1)/2,i=(e[1]??1)/2,a=(e[2]??1)/2;r([[o-n,s-i,c-a],[o+n,s-i,c-a],[o+n,s-i,c+a],[o-n,s-i,c+a]],!0),r([[o-n,s+i,c-a],[o+n,s+i,c-a],[o+n,s+i,c+a],[o-n,s+i,c+a]],!0);for(let[e,t]of[[-1,-1],[1,-1],[1,1],[-1,1]])r([[o+e*n,s-i,c+t*a],[o+e*n,s+i,c+t*a]])}else if(t.shape===`sphere`){let e=t.radius??.5;i(o,s,c,e,`xz`),i(o,s,c,e,`xy`),i(o,s,c,e,`yz`)}else if(t.shape===`capsule`){let e=t.radius??.4,n=(t.height??1)/2;i(o,s+n,c,e,`xz`),i(o,s-n,c,e,`xz`);for(let[t,i]of[[e,0],[-e,0],[0,e],[0,-e]])r([[o+t,s-n,c+i],[o+t,s+n,c+i]])}}e.restore()}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()}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=XN(e),r=this.renderer2d.screenFromWorld(n.x,n.y);return{x:r.x-12,y:r.y-12,w:24,h:24}}drawCollider(e,t,n){if(!this.renderer2d)return;let r=XN(t),i=n.offset??[0,0],a=this.renderer2d.screenFromWorld(r.x+(i[0]??0),r.y+(i[1]??0)),o=this.renderer2d.view().zoom;e.strokeStyle=zN,e.lineWidth=1.5,e.setLineDash([]);let s=n.shape;if(s===`rect`){let t=n.size??[32,32],r=(t[0]??32)/2*o,i=(t[1]??32)/2*o;e.strokeRect(a.x-r,a.y-i,r*2,i*2)}else if(s===`circle`){let t=(n.radius??16)*o;e.beginPath(),e.arc(a.x,a.y,t,0,Math.PI*2),e.stroke()}else if(s===`capsule`){let t=(n.radius??16)*o,r=(n.height??32)/2*o;e.beginPath(),e.arc(a.x,a.y-r,t,Math.PI,0),e.arc(a.x,a.y+r,t,0,Math.PI),e.closePath(),e.stroke()}e.setLineDash([])}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=FN(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:NN(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=PN(i,NN(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=AN(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]]=BN(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=BN(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>BN(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=jN(e,c,l);if(u)_[d[t.axis]]=BN(h((a[d[t.axis]]??0)+n));else{let e=YN(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]=BN(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=BN(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=BN(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=YN(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=>BN(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),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);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=YN(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(){if(this.rendererDim===`3d`){let e=new Ca;for(let[t]of this.pathOf){let n=t._object3D;n&&(e.expandByObject(n),e.expandByPoint(n.getWorldPosition(GN)))}if(e.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let t=e.getCenter(new V),n=e.getSize(new V);this.orbit.target=[t.x,t.y,t.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let e=this.editCanvas.clientWidth||960,t=this.editCanvas.clientHeight||540,n=1/0,r=1/0,i=-1/0,a=-1/0;for(let[e]of this.pathOf){let t=e.position;if(!Array.isArray(t))continue;let o=XN(e);n=Math.min(n,o.x),r=Math.min(r,o.y),i=Math.max(i,o.x),a=Math.max(a,o.y)}if(!Number.isFinite(n))return;let o=(n+i)/2,s=(r+a)/2,c=Math.max(i-n+200,200),l=Math.max(a-r+200,200),u=Math.min(2,Math.min(e/c,t/l));this.renderer2d.viewOverride={cx:o,cy:s,zoom:u}}async play(e){if(this.playing)return null;let t=structuredClone(e);$N(t.root),nP(t);let n;try{n=St(structuredClone(t),{declareConnectionSignals:!0})}catch{delete t.connections;try{n=St(structuredClone(t))}catch(e){return e instanceof Error?e.message:String(e)}}let r=new je;r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new sm({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await mp(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>mm);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders}else{this.playRenderer=new IO({canvas:this.playCanvas,engine:r});let{enablePhysics3D:e}=await mp(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>KO);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders}}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=null,this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}},zN=`rgba(0, 255, 110, 0.95)`;function BN(e){return Math.round(e*100)/100}var VN=new V(0,1,0),HN=new V,UN=new V,WN=new B,GN=new V,KN=new U,qN=new V,JN=new V;function YN(e,t,n){let r=e._object2D?.parent;return r?(KN.copy(r.matrixWorld).invert(),qN.set(t,-n,0).applyMatrix4(KN),JN.set(0,0,0).applyMatrix4(KN),{x:qN.x-JN.x,y:-(qN.y-JN.y)}):{x:t,y:n}}function XN(e){let t=e._object2D;if(t)return t.getWorldPosition(GN),{x:GN.x,y:-GN.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 ZN(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=ZN(t);if(e)return e}return null}function QN(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=QN(t);if(e)return e}return null}function $N(e){if(typeof e!=`object`||!e)return;let t=e;delete t.script;for(let e of t.children??[])$N(e)}var eP=null;function tP(){if(eP)return eP;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 eP=e.toDataURL(),eP}function nP(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=tP())}lt(),Yp(),yD(),nk();var $=e=>{let t=document.querySelector(e);if(!t)throw Error(`missing ${e}`);return t};async function rP(){let e=await lk();$(`#engine-version`).textContent=`incanto@${e.version}`,eM($(`#popover`)),lA(),$(`#docs-btn`).addEventListener(`click`,()=>sA());let t=$(`#lang-btn`),n=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],r=()=>{$(`#lang-current`).textContent=_k()===`ko`?`한국어`:`EN`};r(),t.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:r}of n){let n=document.createElement(`button`);n.type=`button`,n.className=`menu-item`;let i=document.createElement(`span`);i.textContent=r;let a=document.createElement(`span`);a.textContent=_k()===t?`✓`:``,a.className=`lang-check`,n.append(i,a),n.addEventListener(`click`,()=>{e.remove(),vk(t)}),e.appendChild(n)}document.body.appendChild(e);let r=t.getBoundingClientRect();e.style.left=`${r.left}px`,e.style.top=`${r.bottom+6}px`;let i=n=>{e.contains(n.target)||n.target===t||(e.remove(),document.removeEventListener(`pointerdown`,i,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,i,!0),0)}),yk(()=>{r(),uA(),i.select(i.selection)});let i=new XM({format:1,type:`scene`,name:``,root:null}),a=$(`#tree`),o=$(`#inspector`),s=$(`#save-btn`),c=$(`#undo-btn`),l=$(`#play-btn`),u=$(`#error-banner`),d=$(`#play-notice`),f=$(`#add-type`),p=$(`#picker`),m=$(`#picker-list`),h=$(`#scenes-btn`),g=e.input,_=e.output,v,y=!1,b=e=>{u.hidden=!1,u.textContent=e,eA.error(e)},x={on:!1,brush:`0`},S=e=>{let t=0,n=0,r=i.working.root,a=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};a(r);for(let t of e)r=r?.children?.[t],a(r);return{x:t,y:n}},C=(e,t)=>{let n=i.selection,r=i.nodeAt(n);if(!n||r?.type!==`TileMap2D`)return;let{cx:a,cy:o}=rM(S(n),Number(r.props?.tileSize??32),e,t),s=r.props?.cells??[],c=iM(s,a,o,x.brush);!c||JSON.stringify(c)===JSON.stringify(s)||i.mutate(()=>{r.props||={},r.props.cells=c},{path:n,key:`cells`,value:c})},w=()=>{let e=i.nodeAt(i.selection);x.on&&e?.type!==`TileMap2D`&&(x.on=!1),T.setPaintHandler(x.on?C:null)},T=new RN($(`#viewport`),$(`#overlay`),$(`#play-canvas`),{onPick:(e,t)=>i.select(e??null,t),onNodeMoved:(e,t)=>re(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>re(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>re(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>re(e,`scale`,t,[1,1,1]),onNodeRotated2D:(e,t)=>ne(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>re(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])$(`#tool-${t}`).classList.toggle(`active`,t===e)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),l.classList.toggle(`stop`,e),l.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`,d.hidden=!e,e&&(d.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:b}),E=ge().sort(),D=``,O=e=>{if(e===D)return;D=e,f.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 nA)t.includes(e)||t.push(e);for(let e of t){let t=nA.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of E.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&f.appendChild(n)}f.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};O(`2d`);let ee=()=>{let e=i.selection??[];for(let t of f.querySelectorAll(`option`)){let n=structuredClone(i.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=T.validate(n)!==null}};f.addEventListener(`mousedown`,ee),f.addEventListener(`focus`,ee);let k=!1,te=()=>{if(!y)return;hN(a,i),Mk($(`#asset-tree`),i),o.textContent=``,Nk(o,i,fe)||cM(o,i,{modelRefs:()=>aP(i,`model`),animationsForSelection:()=>i.selection?T.modelAnimationsAt(i.selection):[],assetRefs:e=>oP(i,e),addAsset:(e,t)=>sP(i,e,t),confirm:fe,paint:{active:()=>x.on,brush:()=>x.brush,toggle:()=>{x.on=!x.on,w(),te()},setBrush:e=>{x.brush=e,te()}}}),O(i.working.dimension??`2d`),$(`#hints`).hidden=(i.working.dimension??`2d`)===`3d`,$(`#hints-3d`).hidden=(i.working.dimension??`2d`)!==`3d`,T.setSelection(i.selection,i.extra),w();let e=i.pendingLivePatch;if(i.pendingLivePatch=null,!T.playing)if(e&&T.patchProp(i.working,e.path,e.key,e.value))u.hidden=!0;else{let e=T.apply(i.working);u.hidden=e===null,e!==null&&b(e)}s.disabled=!i.dirty||!i.working.root,s.title=i.working.root?``:`Add a root node before saving`,c.disabled=!i.canUndo,i.dirty!==k&&(k=i.dirty,eA.change(i.dirty))};i.onChange(te),i.validator=e=>T.validate(e),i.onError=b;let ne=(e,t,n,r)=>{let a=i.nodeAt(e);a&&i.mutate(()=>{a.props||={},n===r?(delete a.props[t],Object.keys(a.props).length===0&&delete a.props):a.props[t]=n},{path:e,key:t,value:n})},re=(e,t,n,r)=>{let a=i.nodeAt(e);a&&i.mutate(()=>{a.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete a.props[t],Object.keys(a.props).length===0&&delete a.props):a.props[t]=n},{path:e,key:t,value:n})},ie=async(t,n,r)=>{T.playing&&T.stop();let a=await pk(t);v=t,g=n,_=r,y=!0,$(`#file-path`).textContent=t??n,$(`#file-chip`).title=`input: ${n}\noutput: ${r}`,p.hidden=!0,i.reset(a),e.mode===`project`&&eA.open(n,r)},ae=async()=>{let e=await uk();if(m.textContent=``,e.length===0){let e=document.createElement(`div`);e.className=`tree-row`,e.textContent=`no *.scene.json found — create one below`,m.appendChild(e)}for(let t of e){let e=document.createElement(`div`);e.className=`tree-row`,e.textContent=t.rel,e.addEventListener(`click`,()=>{ie(t.rel,t.abs,t.abs).catch(e=>b(e instanceof Error?e.message:String(e)))}),m.appendChild(e)}p.hidden=!1},oe=()=>{p.hidden=!0};if($(`#picker-close`).addEventListener(`click`,oe),p.addEventListener(`pointerdown`,e=>{e.target===p&&oe()}),$(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=$(`#picker-path`).value.trim();if(e)try{let t=await dk(e.endsWith(`.scene.json`)?e:`${e}.scene.json`);await ie(t.rel,t.abs,t.abs)}catch(e){b(e instanceof Error?e.message:String(e))}})()}),e.mode===`project`){h.hidden=!1,h.addEventListener(`click`,()=>void ae());let e=await uk(),t=e.length===1?e[0]:void 0;t?await ie(t.rel,t.abs,t.abs):await ae()}else await ie(void 0,e.input,e.output);$(`#add-btn`).addEventListener(`click`,()=>{let e=i.selection??[],t=f.value,n=i.insertNode({name:t,type:t},e);n&&i.select(n)});let se=$(`#generate`);Jj(i),$(`#generate-btn`).addEventListener(`click`,()=>Kj(i));let ce=$(`#confirm`),le=e=>{if(i.selection===null&&e.length===0){b(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=i.working.root;if(!e)return;let t=iP(e);fe(`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`,()=>i.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=i.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=i.nodeAt(t);return e+(n?iP(n):0)},0);if(n>0){fe(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(i.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{i.removeNodes(e)&&i.select(t)});return}i.removeNodes(e)&&i.select(t);return}$(`#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=$(`#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)}$(`#confirm-title`).textContent=`still referenced`,$(`#confirm-delete`).textContent=`unlink & delete`,ce.hidden=!1,ue={selections:e,parentOfFirst:t}},ue=null,de=null;function fe(e,t,n){$(`#confirm-title`).textContent=`are you sure?`,$(`#confirm-text`).textContent=e,$(`#confirm-list`).textContent=``,$(`#confirm-delete`).textContent=t,de=n,ce.hidden=!1}function A(){ce.hidden=!0,ue=null,de=null}$(`#confirm-close`).addEventListener(`click`,A),$(`#confirm-cancel`).addEventListener(`click`,A),ce.addEventListener(`pointerdown`,e=>{e.target===ce&&A()}),$(`#confirm-delete`).addEventListener(`click`,()=>{if(de){de(),A();return}ue&&i.removeNodesUnlinking(ue.selections)&&i.select(ue.parentOfFirst),A()}),uN(le),$(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),i.startAddingAsset()}),$(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),i.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`)))}$(`#delete-btn`).addEventListener(`click`,()=>{le(i.allSelections().filter(e=>e.length>0))}),l.addEventListener(`click`,()=>{if(T.playing){T.stop(),te();return}T.play(i.working).then(e=>{e&&b(e)})});for(let e of[`move`,`rotate`,`scale`])$(`#tool-${e}`).addEventListener(`click`,()=>T.setMode(e));T.setMode(`move`);let pe=$(`#tool-colliders`),me=`incanto-editor-show-colliders`,j=e=>{T.showColliders=e,pe.classList.toggle(`active`,e),localStorage.setItem(me,e?``:`0`)};j(localStorage.getItem(me)!==`0`),pe.addEventListener(`click`,()=>j(!T.showColliders));let he=$(`#hints-dock`),_e=`incanto-editor-hints-open`;he.classList.toggle(`open`,localStorage.getItem(_e)===`1`),$(`#hints-toggle`).addEventListener(`click`,()=>{let e=he.classList.toggle(`open`);localStorage.setItem(_e,e?`1`:``)}),$(`#fit-btn`).addEventListener(`click`,()=>T.zoomToFit()),$(`#gameview-btn`).addEventListener(`click`,()=>T.gameView()),s.addEventListener(`click`,()=>{(async()=>{try{await mk(i.working,v),i.markSaved(),eA.save(g,_,i.working)}catch(e){b(e instanceof Error?e.message:String(e))}})()}),c.addEventListener(`click`,()=>i.undo()),window.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&T.cancelActiveDrag(),e.key===`Escape`&&!$(`#docs`).hidden){cA();return}if(e.key===`Escape`&&!ce.hidden){A();return}if(e.key===`Escape`&&!se.hidden){qj();return}if(e.key===`Escape`&&!p.hidden){oe();return}if(e.key===`Escape`&&T.playing){T.stop(),te();return}if(T.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),i.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),s.disabled||s.click()):!t&&e.code===`KeyF`?T.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?T.gameView():!t&&e.code===`KeyW`?T.setMode(`move`):!t&&e.code===`KeyE`?T.setMode(`rotate`):!t&&e.code===`KeyR`&&T.setMode(`scale`)}),te(),eA.ready(g,_,e.version)}function iP(e){let t=0;for(let n of e.children??[])t+=1+iP(n);return t}function aP(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function oP(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 sP(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}`}rP().catch(e=>{let t=document.querySelector(`#error-banner`);t&&(t.hidden=!1,t.textContent=e instanceof Error?e.message:String(e))});export{mp as t};
7417
+ `}},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] }`}},sM=null;function cM(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=oM[r.dataset.help??``];if(!i)return;if(!e.hidden&&sM===r){e.hidden=!0;return}sM=r,e.textContent=``;let a=document.createElement(`h4`);a.textContent=Ok(i.title);let o=document.createElement(`div`);if(o.textContent=Ok(i.body),e.append(a,o),i.example){let t=document.createElement(`pre`);t.textContent=i.example,e.appendChild(t)}if(i.copy){let t=document.createElement(`div`);t.className=`pop-actions`;let n=document.createElement(`button`);n.type=`button`,n.className=`linklike`,n.textContent=`⧉ ${i.copy.label}`,n.addEventListener(`click`,()=>{navigator.clipboard.writeText(i.copy?.text??``),n.textContent=`✓ copied`}),t.appendChild(n),e.appendChild(t)}e.hidden=!1;let s=r.getBoundingClientRect();e.style.left=`${Math.max(8,Math.min(innerWidth-300-8,s.left-300+20))}px`,e.style.top=`${Math.min(innerHeight-60,s.bottom+8)}px`})}function lM(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 uM=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 dM(e,t,n,r){return{cx:Math.floor((n-e.x)/t),cy:Math.floor((r-e.y)/t)}}function fM(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 pM(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 mM=uM;function hM(e){return(e.kind===`foliage`||e.kind===`tile`)&&!e.animation}function gM(e,t,n){if(e.textContent=``,t.selection===null){vM(e,t,n);return}let r=t.nodeAt(t.selection);r&&wM(e,t,r,n)}var _M=[`input`,`multiplayer`];function vM(e,t,n){e.appendChild(YM(`scene`)),e.appendChild($M(`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(ZM(`dimension`,r)),e.appendChild(YM(`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(tN(`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(YM(`environment`)),yM(e,t),e.appendChild(YM(`constants`)),UM(e,t,n),e.appendChild(YM(`advanced`));for(let n of _M)e.appendChild(rN(n,t.working[n],e=>{t.mutate(()=>{e===void 0?delete t.working[n]:t.working[n]=e})}))}function yM(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(bM(`background`,n.background??``,e=>{r({background:e===``?void 0:e})})),e.appendChild(bM(`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(eN(`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(ZM(`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(ZM(`pixel ratio`,s))}function bM(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),ZM(e,r)}function xM(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(ZM(`enabled`,l)),a){n.appendChild(bM(`murk color`,String(o.color??``),e=>c(`color`,e))),n.appendChild(eN(`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(ZM(`caustics`,e))}return n}function SM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.textContent=`material`,n.appendChild(r);let i=t.props?.material??{},a=(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)};n.appendChild(bM(`color`,String(i.color??``),e=>a(`color`,e))),n.appendChild(CM(`roughness`,Number(i.roughness??1),e=>a(`roughness`,e))),n.appendChild(CM(`metalness`,Number(i.metalness??0),e=>a(`metalness`,e))),n.appendChild(bM(`emissive`,String(i.emissive??``),e=>a(`emissive`,e))),n.appendChild(CM(`emissive power`,Number(i.emissiveIntensity??1),e=>a(`emissiveIntensity`,e===1?void 0:e),2)),n.appendChild(CM(`opacity`,Number(i.opacity??1),e=>a(`opacity`,e===1?void 0:e))),n.appendChild(CM(`clearcoat`,Number(i.clearcoat??0),e=>a(`clearcoat`,e===0?void 0:e))),n.appendChild(CM(`clearcoat rough`,Number(i.clearcoatRoughness??0),e=>a(`clearcoatRoughness`,e===0?void 0:e))),n.appendChild(CM(`reflection`,Number(i.envMapIntensity??1),e=>a(`envMapIntensity`,e===1?void 0:e),3));let o=document.createElement(`input`);o.type=`checkbox`,o.checked=i.wireframe===!0,o.addEventListener(`change`,()=>a(`wireframe`,o.checked||void 0)),n.appendChild(ZM(`wireframe`,o));let s=document.createElement(`input`);s.type=`checkbox`,s.checked=i.flatShading===!0,s.addEventListener(`change`,()=>a(`flatShading`,s.checked||void 0)),n.appendChild(ZM(`flatShading`,s));let c=document.createElement(`input`);c.type=`checkbox`,c.checked=i.depthTest===!1,c.addEventListener(`change`,()=>{a(`depthTest`,c.checked?!1:void 0),a(`depthWrite`,c.checked?!1:void 0)}),n.appendChild(ZM(`draw on top (decal)`,c)),n.appendChild(PM(`map (texture)`,String(i.map??``),FM(e=>hM(e)&&!e.name.includes(`normal`)&&!e.name.includes(`roughness`)),e=>a(`map`,e.trim()),{placeholder:`built-in or custom URL`})),n.appendChild(PM(`normal map`,String(i.normalMap??``),FM(e=>hM(e)&&e.name.includes(`normal`)),e=>a(`normalMap`,e.trim()),{placeholder:`built-in or custom URL`}));let l=!!(i.map||i.normalMap),u=Array.isArray(i.repeat)?i.repeat:[1,1],d=tN(`repeat [u,v]`,[u[0]??1,u[1]??1],e=>{let[t,n]=e;!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1||!t&&!n?a(`repeat`,void 0):a(`repeat`,[t,n])});return d.title=l?`Texture tiling across the mesh UVs.`:`Only takes effect with a map/normal map set (engine validates).`,n.appendChild(d),n}function CM(e,t,n,r=1){let i=document.createElement(`div`);i.className=`slider-row`;let a=document.createElement(`input`);a.type=`range`,a.min=`0`,a.max=String(r),a.step=`0.05`,a.value=String(Number.isFinite(t)?t:0);let o=document.createElement(`input`);return o.type=`number`,o.step=`0.05`,o.min=`0`,o.max=String(r),o.value=a.value,a.addEventListener(`input`,()=>{o.value=a.value}),a.addEventListener(`change`,()=>n(Number(a.value))),o.addEventListener(`change`,()=>{a.value=o.value,n(Number(o.value))}),i.append(a,o),ZM(e,i)}function wM(e,t,n,r){if(e.appendChild(YM(n.type??`instance`)),e.appendChild(TM(n)),e.appendChild($M(`name`,n.name??``,e=>{e.trim()!==``&&t.mutate(()=>{n.name=e.trim()})})),n.type===`TileMap2D`&&r?.paint&&e.appendChild(nN(n,r.paint)),n.type){let i;try{i=ge(n.type)}catch{i={}}for(let[a,o]of Object.entries(i))if(a===`collider`)e.appendChild(kM(t,n,o.default));else if(a===`material`)e.appendChild(SM(t,n));else if(n.type===`ModelInstance3D`&&a===`model`&&r)e.appendChild(MM(`model`,String(n.props?.model??``),r.modelRefs(),e=>AM(t,n,`model`,e,``)));else if(n.type===`ModelInstance3D`&&a===`animation`&&r)e.appendChild(MM(`animation`,String(n.props?.animation??``),r.animationsForSelection(),e=>AM(t,n,`animation`,e,``)));else if(n.type===`Tree3D`&&a===`leafTexture`)e.appendChild(PM(`leaf texture`,String(n.props?.leafTexture??``),FM(e=>e.name.startsWith(`leaves_`)),e=>AM(t,n,`leafTexture`,e.trim(),``),{placeholder:`default (per-type) or URL`}));else if(n.type===`Terrain3D`&&a===`textureBase`)e.appendChild(PM(`texture base`,String(n.props?.textureBase??o.default??``),LM,e=>AM(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(RM(t,n,a,r,i))}else n.type===`AudioPlayer`&&a===`src`?e.appendChild(PM(`src (audio file)`,String(n.props?.src??``),IM(),e=>AM(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."})):n.type===`Flowers3D`&&a===`varieties`?e.appendChild(zM(t,n)):n.type===`Water3D`&&a===`underwater`?e.appendChild(xM(t,n)):e.appendChild(GM(t,n,a,o.default,o.options))}e.appendChild(YM(`structure`)),e.appendChild(EM(t,n)),e.appendChild(DM(t,n)),e.appendChild(OM(t,n))}function TM(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 EM(e,t){let n=document.createElement(`label`);n.className=`field wide`;let r=document.createElement(`span`);r.append(`groups `,lM(`groups`));let i=document.createElement(`div`);i.className=`chips`;for(let n of t.groups??[])i.appendChild(XM(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 DM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`script `,lM(`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($M(`name`,a.name??``,n=>{e.mutate(()=>{t.script.name=n.trim()})})),n.appendChild(rN(`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 OM(e,t){let n=document.createElement(`div`);n.className=`subcard`;let r=document.createElement(`div`);r.className=`subcard-head`,r.append(`network `,lM(`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(ZM(`mode`,a)),i?.mode===`owner`){let r=document.createElement(`div`);r.className=`chips`;for(let n of i.sync??[])r.appendChild(XM(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(eN(`throttle ms`,i.throttleMs??50,n=>{e.mutate(()=>{t.network.throttleMs=n})}))}return n}function kM(e,t,n){let r=document.createElement(`div`);r.className=`subcard`;let i=document.createElement(`div`);i.className=`subcard-head`,i.append(`collider `,lM(`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(ZM(`shape`,l)),a.shape===`rect`||a.shape===`box`?r.appendChild(tN(`size`,a.size??(s?[1,1,1]:[32,32]),e=>o({...a,size:e}))):a.shape===`circle`||a.shape===`sphere`?r.appendChild(eN(`radius`,a.radius??(s?.5:16),e=>o({...a,radius:e}))):a.shape===`capsule`&&(r.appendChild(eN(`radius`,a.radius??12,e=>o({...a,radius:e}))),r.appendChild(eN(`height`,a.height??16,e=>o({...a,height:e})))),a.shape&&r.appendChild(tN(`offset`,a.offset??(s?[0,0,0]:[0,0]),e=>o({...a,offset:e}))),r}function AM(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 jM=0;function MM(e,t,n,r){let i=document.createElement(`input`);i.type=`text`,i.value=t;let a=`suggest-${jM++}`;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=ZM(e,i);return s.appendChild(o),s}var NM=0;function PM(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`);l.className=`asset-control`,l.append(s,c),a.appendChild(l);let u=document.createElement(`div`);u.className=`asset-panel`,u.hidden=!0;let d=document.createElement(`input`);d.type=`text`,d.className=`asset-search`,d.placeholder=`search ${n.length} built-in${n.length===1?``:`s`}…`;let f=document.createElement(`div`);f.className=`asset-options`,u.append(d,f),a.appendChild(u);let p=e=>{f.textContent=``;let t=e.trim().toLowerCase(),i=n.filter(e=>t===``||e.label.toLowerCase().includes(t)||(e.hint?.toLowerCase().includes(t)??!1)||e.value.toLowerCase().includes(t));if(i.length===0){let e=document.createElement(`div`);e.className=`asset-empty`,e.textContent=`no match — type a custom URL above`,f.appendChild(e);return}for(let e of i){let t=document.createElement(`button`);t.type=`button`,t.className=`asset-option`;let n=document.createElement(`strong`);if(n.textContent=e.label,t.appendChild(n),e.hint){let n=document.createElement(`small`);n.textContent=e.hint,t.appendChild(n)}t.addEventListener(`click`,()=>{s.value=e.value,u.hidden=!0,r(e.value)}),f.appendChild(t)}};if(c.addEventListener(`click`,()=>{u.hidden=!u.hidden,u.hidden||(p(d.value),d.focus())}),d.addEventListener(`input`,()=>p(d.value)),d.addEventListener(`keydown`,e=>{e.key===`Escape`&&(u.hidden=!0)}),i.note){let e=document.createElement(`div`);e.className=`muted-note asset-note`,e.textContent=i.note,a.appendChild(e)}return s.id=`asset-input-${NM++}`,a.htmlFor=s.id,a}function FM(e){return mM.filter(e).map(e=>({label:e.name,value:e.url,hint:`${e.kind} · ${e.description.slice(0,70)}`}))}function IM(){return mM.filter(e=>e.kind===`audio`).map(e=>({label:e.name,value:e.url,hint:`audio · ${e.description.slice(0,70)}`}))}var LM=[{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 RM(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=mM.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 PM(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)}AM(e,t,n,`$${r.addAsset(a.name,i).replace(/^\$/,``)}`,``);return}AM(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."})}function zM(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=Gx.filter(e=>i.has(e));AM(e,t,`varieties`,n.length===0||n.length===Gx.length?[]:n,[])};for(let e of Gx){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 Gx)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 BM=[[`number`,()=>0],[`text`,()=>``],[`boolean`,()=>!1],[`color`,()=>`#ffffff`],[`vec2`,()=>[0,0]],[`vec3`,()=>[0,0,0]]];function VM(e,t){let n=0,r=e=>{if(ft(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 HM(e,t,n){let r=e=>{if(ft(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 UM(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&&HM(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=VM(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(WM(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 BM){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,(BM.find(([e])=>e===u.value)?.[1]??(()=>0))()),l.value=``)}),c.append(l,u,d),e.appendChild(c)}function WM(e,t,n){let r=ue(t);if(r===`number`)return eN(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)),ZM(e,r)}return r===`array`&&Array.isArray(t)&&t.every(e=>typeof e==`number`)?tN(e,t,e=>n(e)):r===`string`?$M(e,String(t),e=>n(e)):rN(e,t,e=>n(e??null),JSON.stringify(t))}function GM(e,t,n,r,i){let a=t.props?.[n]??r,o=ue(r),s=o===`number`||o===`boolean`||o===`string`||o===`array`,c=i=>{let a=ft(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&&s&&!a?{path:e.selection,key:n,value:i}:void 0)},l=KM(e,o,r);if(ft(a))return qM(n,a[`@const`],l,c,r);let u=e=>l.length>0?JM(e,l,c):e;if(o===`number`)return u(eN(n,a,e=>c(e),()=>c(r)));if(o===`boolean`){let e=document.createElement(`input`);return e.type=`checkbox`,e.checked=a===!0,e.addEventListener(`change`,()=>c(e.checked)),u(ZM(n,e))}return o===`string`?i&&i.length>0?u(QM(n,String(a??``),i,e=>c(e))):u($M(n,String(a??``),e=>c(e))):o===`array`&&Array.isArray(r)&&r.length>0&&r.every(e=>typeof e==`number`)?u(tN(n,a??r,e=>c(e))):rN(n,a===r?void 0:a,e=>{c(e===void 0?r:e)},JSON.stringify(r))}function KM(e,t,n){let r=e.working.constants??{};return Object.keys(r).filter(e=>{let i=r[e];return ue(i)===t?t===`array`&&Array.isArray(n)&&Array.isArray(i)?i.length===n.length:!0:!1})}function qM(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=ZM(`🔗 ${e}`,a);return c.classList.add(`const-bound`),c}function JM(e,t,n){let r=document.createElement(`select`);r.className=`const-picker`,r.title=`Bind to a named constant`;let i=document.createElement(`option`);i.value=``,i.textContent=`🔗`,r.appendChild(i);for(let e of t){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}return r.value=``,r.addEventListener(`change`,()=>{r.value&&n({"@const":r.value})}),e.appendChild(r),e}function YM(e,t){let n=document.createElement(`div`);n.className=`section-title`,n.textContent=e,t&&n.appendChild(lM(t));let r=document.createElement(`span`);return r.className=`rule`,n.appendChild(r),n}function XM(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 ZM(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 QM(e,t,n,r){let i=document.createElement(`select`);for(let e of n.includes(t)?n:[t,...n]){let n=document.createElement(`option`);n.value=e,n.textContent=e,e===t&&(n.selected=!0),i.appendChild(n)}return i.addEventListener(`change`,()=>r(i.value)),ZM(e,i)}function $M(e,t,n){let r=document.createElement(`input`);return r.type=`text`,r.value=t,r.addEventListener(`change`,()=>n(r.value)),ZM(e,r)}function eN(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)}),ZM(e,i)}function tN(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)}),ZM(e,r)}function nN(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 pM(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 rN(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=ZM(e,i);return a.className=`field wide`,a}var iN=class{working;selection=[];extra=[];validator=null;selectedAsset=null;selectedGroup=null;pendingGroups=new Set;pendingLivePatch=null;addingAsset=!1;addingGroup=!1;newAssetGroup=``;newGroupParent=``;startAddingAsset(){this.addingAsset=!0,this.addingGroup=!1,this.newAssetGroup=this.selectedGroup??``,this.clearFocus()}startAddingGroup(){this.addingGroup=!0,this.addingAsset=!1,this.newGroupParent=this.selectedGroup??``,this.clearFocus()}cancelAddForms(){this.addingAsset=!1,this.addingGroup=!1}onError=null;original;undoStack=[];listeners=new Set;constructor(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&aN(this.working.root)}get dirty(){return JSON.stringify(this.working)!==this.original}get canUndo(){return this.undoStack.length>0}nodeAt(e){if(e===null)return null;let t=this.working.root;for(let n of e)t=t?.children?.[n];return t??null}parentOf(e){return e.length===0?null:this.nodeAt(e.slice(0,-1))}mutate(e,t){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?r(i):(this.undoStack.push(t),this.undoStack.length>100&&this.undoStack.shift(),this.emit(),n)}moveNode(e,t,n){return this.moveNodes([e],t,n)?.[0]??null}moveNodes(e,t,n){let r=uN(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)fN(i,e);let e,t;if(n===`into`)e=o,e.children||=[],t=e.children.length;else{let r=dN(i,o);if(!r)return null;e=r.parent,t=r.index+ +(n===`after`)}let r=[];a.forEach((n,r)=>{n.name=mN(e,n.name??`Node`),e.children?.splice(t+r,0,n)});for(let e of a){let t=pN(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=mN(n,t.name??`Node`),oN(r);let i=e[e.length-1]+1;return n.children?.splice(i,0,r),[...e.slice(0,-1),i]})}removeNodes(e){let t=uN(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)fN(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 oN(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=mN(n,r.name??`Node`),oN(r),n.children||=[],n.children.push(r),[...t,n.children.length-1]}):null}findRemovalReferences(e){let t=uN(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=uN(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&&sN(this.working,a,i);for(let e of i)fN(r,e);return!0})===!0}reset(e){this.working=e,this.original=JSON.stringify(e),this.working.root&&aN(this.working.root),this.undoStack=[],this.selection=[],this.emit()}markSaved(){this.original=JSON.stringify(this.working),this.emit()}emitChange(){this.emit()}clearFocus(){this.selection=null,this.extra=[],this.selectedAsset=null,this.selectedGroup=null,this.emit()}selectAsset(e){this.selectedAsset=e,e!==null&&(this.cancelAddForms(),this.selectedGroup=null,this.selection=null,this.extra=[]),this.emit()}selectGroup(e){this.selectedGroup=e,e!==null&&(this.cancelAddForms(),this.selectedAsset=null,this.selection=null,this.extra=[]),this.emit()}assetMap(){return this.working.assets??{}}groupCount(e){return Object.keys(this.assetMap()).filter(t=>t.startsWith(`${e}/`)).length}addGroup(e){this.pendingGroups.add(e),this.selectGroup(e)}renameGroup(e,t){if(!t||t===e)return!1;let n=this.assetMap(),r=Object.keys(n).filter(t=>t.startsWith(`${e}/`));return this.pendingGroups.delete(e)&&this.pendingGroups.add(t),this.selectedGroup=t,this.mutate(()=>{for(let i of r){let r=`${t}/${i.slice(e.length+1)}`;n[r]=n[i],delete n[i],cN(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],cN(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(lN)}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 aN(e){(typeof e.uid!=`string`||e.uid===``)&&(e.uid=Ft());for(let t of e.children??[])aN(t)}function oN(e){e.uid=Ft();for(let t of e.children??[])oN(t)}function sN(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):sN(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]:sN(i,t,n))}}function cN(e,t,n){if(Array.isArray(e)){e.forEach((r,i)=>{r===t?e[i]=n:cN(r,t,n)});return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))i===t?e[r]=n:cN(i,t,n)}function lN(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 uN(e){let t=[...e].sort(lN),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 dN(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=dN(n,t);if(e)return e}return null}function fN(e,t){let n=dN(e,t);n?.parent.children?.splice(n.index,1)}function pN(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=pN(r,t);if(e)return[n,...e]}return null}function mN(e,t){let n=new Set((e.children??[]).map(e=>e.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}${r}`);)r+=1;return`${t}${r}`}var hN=new Map(fA.flatMap(e=>e.nodes.map(e=>[e.type,e.summary]))),gN=new Set,_N=null;function vN(e){_N=e}var yN=null,bN=null,xN=null;function SN(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 CN(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}wN(r,t.selection),e.appendChild(TN(r,[],t,``))}function wN(e,t){if(!t)return;let n=e,r=``;for(let e of t){r=r?`${r}/${n.name}`:String(n.name),gN.delete(r);let t=n.children?.[e];if(!t)return;n=t}}function TN(e,t,n,r){let i=r?`${r}/${e.name}`:String(e.name),a=(e.children?.length??0)>0,o=gN.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&&xN!==i;let l=document.createElement(`span`);l.className=`chevron${a?``:` leaf`}${o?` collapsed`:``}`,a?l.appendChild(Mk()):l.textContent=`·`,a&&l.addEventListener(`click`,e=>{e.stopPropagation(),o?gN.delete(i):gN.add(i),n.select(n.selection)});let u=document.createElement(`span`);if(u.className=`tree-icon ${SN(e.type)}`,u.appendChild(jk(e.type)),u.title=e.type??`instance`,u.addEventListener(`click`,t=>{t.stopPropagation(),EN(u,e.type??`instance`)}),c.append(l,u),xN===i){let t=document.createElement(`input`);t.className=`rename-input`,t.value=e.name??``;let r=()=>{xN=null;let r=t.value.trim();r&&r!==e.name?n.mutate(()=>{e.name=r}):n.select(n.selection)};t.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&r(),e.key===`Escape`&&(xN=null,n.select(n.selection))});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])t.addEventListener(e,e=>e.stopPropagation());t.addEventListener(`blur`,r),c.appendChild(t),queueMicrotask(()=>{t.focus(),t.select()})}else{let r=document.createElement(`span`);r.className=`tree-name`,r.textContent=e.name??`(unnamed)`,r.addEventListener(`dblclick`,e=>{e.stopPropagation(),xN=i,n.select(t)}),c.appendChild(r)}if(c.addEventListener(`click`,e=>{a&&!e.metaKey&&!e.ctrlKey&&(o?gN.delete(i):gN.add(i)),n.select(t,{toggle:e.metaKey||e.ctrlKey})}),c.addEventListener(`contextmenu`,e=>{e.preventDefault(),n.isSelected(t)||n.select(t),DN(e.clientX,e.clientY,n,t,i)}),IN(c,t,n),s.appendChild(c),a&&!o){let r=document.createElement(`div`);r.className=`tree-children`,(e.children??[]).forEach((e,a)=>{r.appendChild(TN(e,[...t,a],n,i))}),s.appendChild(r)}return s}function EN(e,t){MN();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=hN.get(t);if(i){let e=document.createElement(`span`);e.textContent=Ok(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`,NN(n)}function DN(e,t,n,r,i){MN();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`,()=>{MN(),t()}),s.appendChild(r)};c(`duplicate${a.length>1?` ×${a.length}`:``}`,()=>{for(let e of[...a].reverse())n.duplicateNode(e)}),c(`rename`,o?()=>{xN=i,n.select(r)}:null,{kbd:`dbl-click`}),s.appendChild(ON()),c(`cut`,r.length>0?()=>kN(n,!0):null),c(`copy`,r.length>0?()=>kN(n,!1):null),c(`paste as child${bN?` (${bN.nodes.length})`:``}`,bN?()=>AN(n,r):null),s.appendChild(ON()),c(`delete`,r.length>0?()=>(_N??(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`,NN(s)}function ON(){let e=document.createElement(`div`);return e.className=`menu-divider`,e}function kN(e,t){let n=e.allSelections().filter(e=>e.length>0).map(t=>e.nodeAt(t)).filter(e=>e!==null);bN={nodes:n.map(e=>JSON.parse(JSON.stringify(e))),cut:t?n:null}}function AN(e,t){if(bN){for(let n of bN.nodes)e.insertNode(n,t);if(bN.cut){let t=e.working.root,n=bN.cut.map(e=>jN(t,e)).filter(e=>e!==null);n.length>0&&e.removeNodes(n),bN={nodes:bN.nodes,cut:null}}}}function jN(e,t){if(e===t)return[];for(let[n,r]of(e.children??[]).entries()){let e=jN(r,t);if(e)return[n,...e]}return null}function MN(){for(let e of document.querySelectorAll(`.floating`))e.remove()}function NN(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 PN(e,t){let n=t.getBoundingClientRect(),r=(e.clientY-n.top)/n.height;return r<.25?`before`:r>.75?`after`:`into`}function FN(e){e.classList.remove(`drop-into`,`drop-before`,`drop-after`)}function IN(e,t,n){e.addEventListener(`dragstart`,r=>{yN=n.isSelected(t)?n.allSelections():[t],r.dataTransfer?.setData(`text/plain`,``),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`),e.classList.add(`dragging`)}),e.addEventListener(`dragend`,()=>{yN=null,e.classList.remove(`dragging`)}),e.addEventListener(`dragover`,n=>{if(!yN||yN.some(e=>e.length<=t.length&&e.every((e,n)=>e===t[n])))return;n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect=`move`),FN(e);let r=t.length===0?`into`:PN(n,e);e.classList.add(`drop-${r}`)}),e.addEventListener(`dragleave`,()=>FN(e)),e.addEventListener(`drop`,r=>{if(FN(e),!yN)return;r.preventDefault();let i=t.length===0?`into`:PN(r,e),a=n.moveNodes(yN,t,i);yN=null,a?.[0]&&n.select(a[0])})}var LN={x:`#fb7185`,y:`#86efac`,z:`#7aa2ff`};function RN(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 zN(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 BN(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 VN(e,t,n){return Math.atan2(n-e.y,t-e.x)*180/Math.PI}function HN(e,t){let n=t-e;for(;n>180;)n-=360;for(;n<=-180;)n+=360;return n}function UN(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 WN(e,t,n){for(let r of t){if(r.points.length<2)continue;let t=n===r.axis;e.strokeStyle=LN[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 GN(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 KN=class{engine;editCanvas;overlay;playCanvas;cb;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;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 je({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.engine.start(),this.engine.updated.connect(()=>this.drawOverlay()),window.addEventListener(`keydown`,e=>{e.key===`Shift`&&(this.shiftHeld=!0)}),window.addEventListener(`keyup`,e=>{e.key===`Shift`&&(this.shiftHeld=!1)}),this.bindPointer()}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);delete t.connections,sP(t.root),uP(t),n=St(t)}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 sm({canvas:this.editCanvas,engine:this.engine}),this.renderer2d.ignoreStatic=!0,this.renderer2d.viewOverride=this.defaultView(e);else{this.renderer3d=new WO({canvas:this.editCanvas,engine:this.engine}),this.renderer3d.ignoreStatic=!0;let t=aP(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 delete t.connections,sP(t.root),uP(t),St(t),null}catch(e){return e instanceof Error?e.message:String(e)}}defaultView(e){let t=oP(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;showColliders=!0;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=iP(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:LN.x},{axis:`y`,sx:0,sy:64,worldPerUnit:64/i,color:LN.y}]}}if(this.rendererDim===`3d`&&this.renderer3d){let t=e._object3D,n=e.position;if(!t||!Array.isArray(n))return null;t.getWorldPosition($N);let r=this.renderer3d.screenFromWorld($N.x,$N.y,$N.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($N.x+t[0]*o,$N.y+t[1]*o,$N.z+t[2]*o);n.behind||i.push({axis:e,sx:n.x-r.x,sy:n.y-r.y,worldPerUnit:o,color:LN[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=iP(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($N);let n={x:$N.x,y:$N.y,z:$N.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 V(r[0]+n*i*Math.sin(e),r[1]+n*Math.sin(t),r[2]+n*i*Math.cos(e)),o=new V(r[0],r[1],r[2]).sub(a).normalize(),s=new V().crossVectors(o,YN).normalize();return{pos:a,right:s,up:new V().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 nx&&(t.current||!e)&&(e=t,t.current))break;let t=e?e._ensureObject3D():null;if(t){t.getWorldPosition(XN),ZN.set(0,0,-1).applyQuaternion(t.getWorldQuaternion(QN));let e=Math.min(40,Math.max(3,this.orbit.dist));this.orbit.target=[XN.x+ZN.x*e,XN.y+ZN.y*e,XN.z+ZN.z*e],this.orbit.dist=e,this.orbit.yaw=Math.atan2(-ZN.x,-ZN.z),this.orbit.pitch=Math.asin(Math.max(-.99,Math.min(.99,-ZN.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 V(1,0,0)],[`y`,new V(0,1,0)],[`z`,new V(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 sw||t instanceof zp||t instanceof uw||t instanceof lD||t instanceof MC)&&t.update(e)}modelAnimationsAt(e){let t=this.nodeAtPath.get(e.join(`.`));return t instanceof sw?t.availableAnimations():[]}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.showColliders&&this.drawColliders3D(e),this.drawGizmo(e),this.drawModeGizmo(e),this.readout&&GN(e,this.readout.x,this.readout.y,this.readout.text);return}if(!this.renderer2d)return;if(this.drawAxes2D(e),this.showColliders)for(let[t]of this.pathOf){let n=t.collider;n&&typeof n==`object`&&`shape`in n&&this.drawCollider(e,t,n)}if(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&&GN(e,this.readout.x,this.readout.y,this.readout.text)}drawModeGizmo(e){if(this.gizmoMode===`rotate`){let t=this.ringLayout();t&&WN(e,t.rings,this.activeRing);return}let t=this.gizmoLayout();t&&BN(e,t,this.gizmoActive,this.gizmoMode===`scale`)}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)}}drawColliders3D(e){let t=this.renderer3d;if(!t)return;e.save(),e.strokeStyle=qN,e.lineWidth=1.5;let n=(e,n,r)=>t.screenFromWorld(e,n,r),r=(t,r=!1)=>{e.beginPath();let i=!1;for(let[r,a,o]of t){let t=n(r,a,o);if(t.behind){i=!1;continue}i?e.lineTo(t.x,t.y):e.moveTo(t.x,t.y),i=!0}r&&e.closePath(),e.stroke()},i=(e,t,n,i,a)=>{let o=[];for(let r=0;r<=32;r++){let s=r/32*Math.PI*2,c=Math.cos(s)*i,l=Math.sin(s)*i;a===`xz`?o.push([e+c,t,n+l]):a===`xy`?o.push([e+c,t+l,n]):o.push([e,t+c,n+l])}r(o)};for(let[e]of this.pathOf){let t=e.collider,n=e._object3D;if(!t||typeof t!=`object`||!(`shape`in t)||!n)continue;n.getWorldPosition($N);let a=t.offset??[0,0,0],o=$N.x+(a[0]??0),s=$N.y+(a[1]??0),c=$N.z+(a[2]??0);if(t.shape===`box`){let e=t.size??[1,1,1],n=(e[0]??1)/2,i=(e[1]??1)/2,a=(e[2]??1)/2;r([[o-n,s-i,c-a],[o+n,s-i,c-a],[o+n,s-i,c+a],[o-n,s-i,c+a]],!0),r([[o-n,s+i,c-a],[o+n,s+i,c-a],[o+n,s+i,c+a],[o-n,s+i,c+a]],!0);for(let[e,t]of[[-1,-1],[1,-1],[1,1],[-1,1]])r([[o+e*n,s-i,c+t*a],[o+e*n,s+i,c+t*a]])}else if(t.shape===`sphere`){let e=t.radius??.5;i(o,s,c,e,`xz`),i(o,s,c,e,`xy`),i(o,s,c,e,`yz`)}else if(t.shape===`capsule`){let e=t.radius??.4,n=(t.height??1)/2;i(o,s+n,c,e,`xz`),i(o,s-n,c,e,`xz`);for(let[t,i]of[[e,0],[-e,0],[0,e],[0,-e]])r([[o+t,s-n,c+i],[o+t,s+n,c+i]])}}e.restore()}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()}pointBounds(e){if(!this.renderer2d)return null;let t=e.position;if(!Array.isArray(t))return null;let n=iP(e),r=this.renderer2d.screenFromWorld(n.x,n.y);return{x:r.x-12,y:r.y-12,w:24,h:24}}drawCollider(e,t,n){if(!this.renderer2d)return;let r=iP(t),i=n.offset??[0,0],a=this.renderer2d.screenFromWorld(r.x+(i[0]??0),r.y+(i[1]??0)),o=this.renderer2d.view().zoom;e.strokeStyle=qN,e.lineWidth=1.5,e.setLineDash([]);let s=n.shape;if(s===`rect`){let t=n.size??[32,32],r=(t[0]??32)/2*o,i=(t[1]??32)/2*o;e.strokeRect(a.x-r,a.y-i,r*2,i*2)}else if(s===`circle`){let t=(n.radius??16)*o;e.beginPath(),e.arc(a.x,a.y,t,0,Math.PI*2),e.stroke()}else if(s===`capsule`){let t=(n.radius??16)*o,r=(n.height??32)/2*o;e.beginPath(),e.arc(a.x,a.y-r,t,Math.PI,0),e.arc(a.x,a.y+r,t,0,Math.PI),e.closePath(),e.stroke()}e.setLineDash([])}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=UN(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:VN(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=HN(i,VN(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=RN(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]]=JN(g((o[d[t.axis]]??1)*n));else for(let e=0;e<r.length;e++)r[e]=JN(g((o[e]??1)*n));i.scale=r,this.readout={x:e.offsetX,y:e.offsetY,text:`×${r.map(e=>JN(e)).join(`, `)}`};return}let _=[...a];if(t.kind===`axis`){let e=r.axes.find(e=>e.axis===t.axis);if(!e)return;let n=zN(e,c,l);if(u)_[d[t.axis]]=JN(h((a[d[t.axis]]??0)+n));else{let e=rP(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]=JN(h((a[0]??0)+(e.x*c-t.x*l)*n)),_[1]=JN(h((a[1]??0)+(e.y*c-t.y*l)*n)),_[2]=JN(h((a[2]??0)+(e.z*c-t.z*l)*n))}else if(this.renderer2d){let e=this.renderer2d.view(),t=rP(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=>JN(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),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);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=rP(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(){if(this.rendererDim===`3d`){let e=new Ca;for(let[t]of this.pathOf){let n=t._object3D;n&&(e.expandByObject(n),e.expandByPoint(n.getWorldPosition($N)))}if(e.isEmpty())this.orbit.target=[0,1,0],this.orbit.dist=10;else{let t=e.getCenter(new V),n=e.getSize(new V);this.orbit.target=[t.x,t.y,t.z],this.orbit.dist=Math.max(2.5,n.length()*.85)}this.syncOrbit();return}if(!this.renderer2d)return;let e=this.editCanvas.clientWidth||960,t=this.editCanvas.clientHeight||540,n=1/0,r=1/0,i=-1/0,a=-1/0;for(let[e]of this.pathOf){let t=e.position;if(!Array.isArray(t))continue;let o=iP(e);n=Math.min(n,o.x),r=Math.min(r,o.y),i=Math.max(i,o.x),a=Math.max(a,o.y)}if(!Number.isFinite(n))return;let o=(n+i)/2,s=(r+a)/2,c=Math.max(i-n+200,200),l=Math.max(a-r+200,200),u=Math.min(2,Math.min(e/c,t/l));this.renderer2d.viewOverride={cx:o,cy:s,zoom:u}}async play(e){if(this.playing)return null;let t=structuredClone(e);sP(t.root),uP(t);let n;try{n=St(structuredClone(t),{declareConnectionSignals:!0})}catch{delete t.connections;try{n=St(structuredClone(t))}catch(e){return e instanceof Error?e.message:String(e)}}let r=new je;r.setScene(n),r.input.attachKeyboard(window),this.playCanvas.hidden=!1;let i=e.dimension??`2d`;try{if(i===`2d`){this.playRenderer=new sm({canvas:this.playCanvas,engine:r});let{enablePhysics2D:e}=await mp(async()=>{let{enablePhysics2D:e}=await Promise.resolve().then(()=>mm);return{enablePhysics2D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders}else{this.playRenderer=new WO({canvas:this.playCanvas,engine:r});let{enablePhysics3D:e}=await mp(async()=>{let{enablePhysics3D:e}=await Promise.resolve().then(()=>ek);return{enablePhysics3D:e}},void 0,import.meta.url),t=await e(r);t.debugDraw=this.showColliders}}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=null,this.playRenderer?.dispose(),this.playRenderer=null,this.playCanvas.hidden=!0,this.cb.onPlayStateChanged(!1),this.lastAppliedKey=null,this.lastGood&&this.apply(this.lastGood)}},qN=`rgba(0, 255, 110, 0.95)`;function JN(e){return Math.round(e*100)/100}var YN=new V(0,1,0),XN=new V,ZN=new V,QN=new B,$N=new V,eP=new U,tP=new V,nP=new V;function rP(e,t,n){let r=e._object2D?.parent;return r?(eP.copy(r.matrixWorld).invert(),tP.set(t,-n,0).applyMatrix4(eP),nP.set(0,0,0).applyMatrix4(eP),{x:tP.x-nP.x,y:-(tP.y-nP.y)}):{x:t,y:n}}function iP(e){let t=e._object2D;if(t)return t.getWorldPosition($N),{x:$N.x,y:-$N.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 aP(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=aP(t);if(e)return e}return null}function oP(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=oP(t);if(e)return e}return null}function sP(e){if(typeof e!=`object`||!e)return;let t=e;delete t.script;for(let e of t.children??[])sP(e)}var cP=null;function lP(){if(cP)return cP;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 cP=e.toDataURL(),cP}function uP(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=lP())}lt(),Yp(),DD(),uk();var $=e=>{let t=document.querySelector(e);if(!t)throw Error(`missing ${e}`);return t};async function dP(){let e=await _k();$(`#engine-version`).textContent=`incanto@${e.version}`,cM($(`#popover`)),_A(),$(`#docs-btn`).addEventListener(`click`,()=>hA());let t=$(`#lang-btn`),n=[{code:`en`,label:`English`},{code:`ko`,label:`한국어`}],r=()=>{$(`#lang-current`).textContent=Tk()===`ko`?`한국어`:`EN`};r(),t.addEventListener(`click`,()=>{document.querySelector(`.lang-menu`)?.remove();let e=document.createElement(`div`);e.className=`context-menu floating lang-menu`;for(let{code:t,label:r}of n){let n=document.createElement(`button`);n.type=`button`,n.className=`menu-item`;let i=document.createElement(`span`);i.textContent=r;let a=document.createElement(`span`);a.textContent=Tk()===t?`✓`:``,a.className=`lang-check`,n.append(i,a),n.addEventListener(`click`,()=>{e.remove(),Ek(t)}),e.appendChild(n)}document.body.appendChild(e);let r=t.getBoundingClientRect();e.style.left=`${r.left}px`,e.style.top=`${r.bottom+6}px`;let i=n=>{e.contains(n.target)||n.target===t||(e.remove(),document.removeEventListener(`pointerdown`,i,!0))};setTimeout(()=>document.addEventListener(`pointerdown`,i,!0),0)}),Dk(()=>{r(),vA(),i.select(i.selection)});let i=new iN({format:1,type:`scene`,name:``,root:null}),a=$(`#tree`),o=$(`#inspector`),s=$(`#save-btn`),c=$(`#undo-btn`),l=$(`#play-btn`),u=$(`#error-banner`),d=$(`#play-notice`),f=$(`#add-type`),p=$(`#picker`),m=$(`#picker-list`),h=$(`#scenes-btn`),g=e.input,_=e.output,v,y=!1,b=e=>{u.hidden=!1,u.textContent=e,cA.error(e)},x={on:!1,brush:`0`},S=e=>{let t=0,n=0,r=i.working.root,a=e=>{let r=e?.props?.position;Array.isArray(r)&&(t+=Number(r[0]??0),n+=Number(r[1]??0))};a(r);for(let t of e)r=r?.children?.[t],a(r);return{x:t,y:n}},C=(e,t)=>{let n=i.selection,r=i.nodeAt(n);if(!n||r?.type!==`TileMap2D`)return;let{cx:a,cy:o}=dM(S(n),Number(r.props?.tileSize??32),e,t),s=r.props?.cells??[],c=fM(s,a,o,x.brush);!c||JSON.stringify(c)===JSON.stringify(s)||i.mutate(()=>{r.props||={},r.props.cells=c},{path:n,key:`cells`,value:c})},w=()=>{let e=i.nodeAt(i.selection);x.on&&e?.type!==`TileMap2D`&&(x.on=!1),T.setPaintHandler(x.on?C:null)},T=new KN($(`#viewport`),$(`#overlay`),$(`#play-canvas`),{onPick:(e,t)=>i.select(e??null,t),onNodeMoved:(e,t)=>ne(e,`position`,t,[0,0]),onNodeScaled:(e,t)=>ne(e,`scale`,t,[1,1]),onNodeMoved3D:(e,t)=>ne(e,`position`,t,[0,0,0]),onNodeScaled3D:(e,t)=>ne(e,`scale`,t,[1,1,1]),onNodeRotated2D:(e,t)=>te(e,`rotation`,t,0),onNodeRotated3D:(e,t)=>ne(e,`rotation`,t,[0,0,0]),onModeChanged:e=>{for(let t of[`move`,`rotate`,`scale`])$(`#tool-${t}`).classList.toggle(`active`,t===e)},onPlayStateChanged:e=>{document.body.classList.toggle(`playing`,e),l.classList.toggle(`stop`,e),l.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`,d.hidden=!e,e&&(d.textContent=`▶ simulating — physics + input live; game scripts run only in your real game. Esc or stop to return.`)},onError:b}),E=he().sort(),D=``,O=e=>{if(e===D)return;D=e,f.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 uA)t.includes(e)||t.push(e);for(let e of t){let t=uA.find(([t])=>t===e)?.[1];if(!t)continue;let n=document.createElement(`optgroup`);n.label=e;for(let e of E.filter(t)){let t=document.createElement(`option`);t.value=e,t.textContent=e,n.appendChild(t)}n.children.length>0&&f.appendChild(n)}f.value=e===`3d`?`MeshInstance3D`:`Sprite2D`};O(`2d`);let k=()=>{let e=i.selection??[];for(let t of f.querySelectorAll(`option`)){let n=structuredClone(i.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=T.validate(n)!==null}};f.addEventListener(`mousedown`,k),f.addEventListener(`focus`,k);let A=!1,ee=()=>{if(!y)return;CN(a,i),Bk($(`#asset-tree`),i),o.textContent=``,Vk(o,i,de)||gM(o,i,{modelRefs:()=>pP(i,`model`),animationsForSelection:()=>i.selection?T.modelAnimationsAt(i.selection):[],assetRefs:e=>mP(i,e),addAsset:(e,t)=>hP(i,e,t),confirm:de,paint:{active:()=>x.on,brush:()=>x.brush,toggle:()=>{x.on=!x.on,w(),ee()},setBrush:e=>{x.brush=e,ee()}}}),O(i.working.dimension??`2d`),$(`#hints`).hidden=(i.working.dimension??`2d`)===`3d`,$(`#hints-3d`).hidden=(i.working.dimension??`2d`)!==`3d`,T.setSelection(i.selection,i.extra),w();let e=i.pendingLivePatch;if(i.pendingLivePatch=null,!T.playing)if(e&&T.patchProp(i.working,e.path,e.key,e.value))u.hidden=!0;else{let e=T.apply(i.working);u.hidden=e===null,e!==null&&b(e)}s.disabled=!i.dirty||!i.working.root,s.title=i.working.root?``:`Add a root node before saving`,c.disabled=!i.canUndo,i.dirty!==A&&(A=i.dirty,cA.change(i.dirty))};i.onChange(ee),i.validator=e=>T.validate(e),i.onError=b;let te=(e,t,n,r)=>{let a=i.nodeAt(e);a&&i.mutate(()=>{a.props||={},n===r?(delete a.props[t],Object.keys(a.props).length===0&&delete a.props):a.props[t]=n},{path:e,key:t,value:n})},ne=(e,t,n,r)=>{let a=i.nodeAt(e);a&&i.mutate(()=>{a.props||={},JSON.stringify(n)===JSON.stringify(r)?(delete a.props[t],Object.keys(a.props).length===0&&delete a.props):a.props[t]=n},{path:e,key:t,value:n})},re=async(t,n,r)=>{T.playing&&T.stop();let a=await xk(t);v=t,g=n,_=r,y=!0,$(`#file-path`).textContent=t??n,$(`#file-chip`).title=`input: ${n}\noutput: ${r}`,p.hidden=!0,i.reset(a),e.mode===`project`&&cA.open(n,r)},ie=async()=>{let e=await vk();if(m.textContent=``,e.length===0){let e=document.createElement(`div`);e.className=`tree-row`,e.textContent=`no *.scene.json found — create one below`,m.appendChild(e)}for(let t of e){let e=document.createElement(`div`);e.className=`tree-row`,e.textContent=t.rel,e.addEventListener(`click`,()=>{re(t.rel,t.abs,t.abs).catch(e=>b(e instanceof Error?e.message:String(e)))}),m.appendChild(e)}p.hidden=!1},ae=()=>{p.hidden=!0};if($(`#picker-close`).addEventListener(`click`,ae),p.addEventListener(`pointerdown`,e=>{e.target===p&&ae()}),$(`#picker-create`).addEventListener(`click`,()=>{(async()=>{let e=$(`#picker-path`).value.trim();if(e)try{let t=await yk(e.endsWith(`.scene.json`)?e:`${e}.scene.json`);await re(t.rel,t.abs,t.abs)}catch(e){b(e instanceof Error?e.message:String(e))}})()}),e.mode===`project`){h.hidden=!1,h.addEventListener(`click`,()=>void ie());let e=await vk(),t=e.length===1?e[0]:void 0;t?await re(t.rel,t.abs,t.abs):await ie()}else await re(void 0,e.input,e.output);$(`#add-btn`).addEventListener(`click`,()=>{let e=i.selection??[],t=f.value,n=i.insertNode({name:t,type:t},e);n&&i.select(n)});let oe=$(`#generate`);nM(i),$(`#generate-btn`).addEventListener(`click`,()=>eM(i));let se=$(`#confirm`),ce=e=>{if(i.selection===null&&e.length===0){b(`The scene itself cannot be deleted — it IS the file.`);return}if(e.length===0){let e=i.working.root;if(!e)return;let t=fP(e);de(`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`,()=>i.deleteRoot());return}let t=e[0]?.slice(0,-1)??[],n=i.findRemovalReferences(e);if(n.length===0){let n=e.reduce((e,t)=>{let n=i.nodeAt(t);return e+(n?fP(n):0)},0);if(n>0){de(`This deletes ${e.length>1?`${e.length} nodes`:`'${String(i.nodeAt(e[0]??[])?.name??``)}'`} AND ${n} descendant node${n===1?``:`s`}.`,`delete ${e.length+n} nodes`,()=>{i.removeNodes(e)&&i.select(t)});return}i.removeNodes(e)&&i.select(t);return}$(`#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=$(`#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)}$(`#confirm-title`).textContent=`still referenced`,$(`#confirm-delete`).textContent=`unlink & delete`,se.hidden=!1,le={selections:e,parentOfFirst:t}},le=null,ue=null;function de(e,t,n){$(`#confirm-title`).textContent=`are you sure?`,$(`#confirm-text`).textContent=e,$(`#confirm-list`).textContent=``,$(`#confirm-delete`).textContent=t,ue=n,se.hidden=!1}function j(){se.hidden=!0,le=null,ue=null}$(`#confirm-close`).addEventListener(`click`,j),$(`#confirm-cancel`).addEventListener(`click`,j),se.addEventListener(`pointerdown`,e=>{e.target===se&&j()}),$(`#confirm-delete`).addEventListener(`click`,()=>{if(ue){ue(),j();return}le&&i.removeNodesUnlinking(le.selections)&&i.select(le.parentOfFirst),j()}),vN(ce),$(`#asset-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),i.startAddingAsset()}),$(`#group-add-btn`).addEventListener(`click`,e=>{e.stopPropagation(),i.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`)))}$(`#delete-btn`).addEventListener(`click`,()=>{ce(i.allSelections().filter(e=>e.length>0))}),l.addEventListener(`click`,()=>{if(T.playing){T.stop(),ee();return}T.play(i.working).then(e=>{e&&b(e)})});for(let e of[`move`,`rotate`,`scale`])$(`#tool-${e}`).addEventListener(`click`,()=>T.setMode(e));T.setMode(`move`);let fe=$(`#tool-colliders`),pe=`incanto-editor-show-colliders`,M=e=>{T.showColliders=e,fe.classList.toggle(`active`,e),localStorage.setItem(pe,e?``:`0`)};M(localStorage.getItem(pe)!==`0`),fe.addEventListener(`click`,()=>M(!T.showColliders));let me=$(`#hints-dock`),ge=`incanto-editor-hints-open`;me.classList.toggle(`open`,localStorage.getItem(ge)===`1`),$(`#hints-toggle`).addEventListener(`click`,()=>{let e=me.classList.toggle(`open`);localStorage.setItem(ge,e?`1`:``)}),$(`#fit-btn`).addEventListener(`click`,()=>T.zoomToFit()),$(`#gameview-btn`).addEventListener(`click`,()=>T.gameView()),s.addEventListener(`click`,()=>{(async()=>{try{await Sk(i.working,v),i.markSaved(),cA.save(g,_,i.working)}catch(e){b(e instanceof Error?e.message:String(e))}})()}),c.addEventListener(`click`,()=>i.undo()),window.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&T.cancelActiveDrag(),e.key===`Escape`&&!$(`#docs`).hidden){gA();return}if(e.key===`Escape`&&!se.hidden){j();return}if(e.key===`Escape`&&!oe.hidden){tM();return}if(e.key===`Escape`&&!p.hidden){ae();return}if(e.key===`Escape`&&T.playing){T.stop(),ee();return}if(T.playing)return;let t=e.target.matches(`input, textarea, select`);(e.metaKey||e.ctrlKey)&&e.key===`z`?(e.preventDefault(),i.undo()):(e.metaKey||e.ctrlKey)&&e.key===`s`?(e.preventDefault(),s.disabled||s.click()):!t&&e.code===`KeyF`?T.zoomToFit():!t&&(e.code===`Digit0`||e.code===`Numpad0`)?T.gameView():!t&&e.code===`KeyW`?T.setMode(`move`):!t&&e.code===`KeyE`?T.setMode(`rotate`):!t&&e.code===`KeyR`&&T.setMode(`scale`)}),ee(),cA.ready(g,_,e.version)}function fP(e){let t=0;for(let n of e.children??[])t+=1+fP(n);return t}function pP(e,t){let n=e.working.assets;return n?Object.entries(n).filter(([,e])=>e?.type===t).map(([e])=>`$${e}`):[]}function mP(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 hP(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}`}dP().catch(e=>{let t=document.querySelector(`#error-banner`);t&&(t.hidden=!1,t.textContent=e instanceof Error?e.message:String(e))});export{mp as t};