@tomorrowevening/hermes 0.1.11 → 0.1.13
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.
- package/dist/hermes.cjs.js +48 -48
- package/dist/hermes.es.js +3785 -3666
- package/package.json +1 -1
- package/types/editor/ThreeEditor.d.ts +1 -1
- package/types/editor/multiView/MultiView.d.ts +1 -1
- package/types/editor/sidePanel/Accordion.d.ts +1 -0
- package/types/utils/math.d.ts +1 -1
- package/types/utils/theatre.d.ts +1 -0
- package/types/utils/three.d.ts +15 -1
package/dist/hermes.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const oe=require("@theatre/core"),
|
|
1
|
+
"use strict";var C0=Object.create;var yd=Object.defineProperty;var E0=Object.getOwnPropertyDescriptor;var A0=Object.getOwnPropertyNames;var R0=Object.getPrototypeOf,N0=Object.prototype.hasOwnProperty;var P0=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of A0(e))!N0.call(o,i)&&i!==t&&yd(o,i,{get:()=>e[i],enumerable:!(s=E0(e,i))||s.enumerable});return o};var F0=(o,e,t)=>(t=o!=null?C0(R0(o)):{},P0(e||!o||!o.__esModule?yd(t,"default",{value:o,enumerable:!0}):t,o));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const oe=require("@theatre/core"),W=require("react"),y=require("three"),go=()=>{},D0=()=>{};function yo(o){return o.substring(0,1).toUpperCase()+o.substring(1)}function sm(o){const e=JSON.stringify(o);return navigator.clipboard.writeText(e),e}function ht(){return Math.round(Math.random()*1e6).toString()}function im(o){return o.r!==void 0&&o.g!==void 0&&o.b!==void 0}function uh(o){const e=Math.round(o.r*255),t=Math.round(o.g*255),s=Math.round(o.b*255),i=l=>{const c=l.toString(16);return c.length===1?"0"+c:c},n=i(e),r=i(t),a=i(s);return"#"+n+r+a}function kl(o,e,t,s){return new(t||(t=Promise))(function(i,n){function r(c){try{l(s.next(c))}catch(h){n(h)}}function a(c){try{l(s.throw(c))}catch(h){n(h)}}function l(c){var h;c.done?i(c.value):(h=c.value,h instanceof t?h:new t(function(u){u(h)})).then(r,a)}l((s=s.apply(o,[])).next())})}const O0=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function xd(o){return o=o.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const nm=typeof window>"u",Fs=(()=>{if(nm)return;const{userAgent:o,platform:e,maxTouchPoints:t}=window.navigator,s=/(iphone|ipod|ipad)/i.test(o),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(o)||s||i,isSafari12:/Version\/12.+Safari/.test(o),isFirefox:/Firefox/.test(o)}})();function B0(o,e,t){if(!t)return[e];const s=function(c){const h=`
|
|
2
2
|
precision highp float;
|
|
3
3
|
attribute vec3 aPosition;
|
|
4
4
|
varying float vvv;
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
|
|
16
16
|
gl_FragColor = enc;
|
|
17
17
|
}
|
|
18
|
-
`,d=c.createShader(35633),p=c.createShader(35632),f=c.createProgram();if(!(p&&d&&f))return;c.shaderSource(d,h),c.shaderSource(p,u),c.compileShader(d),c.compileShader(p),c.attachShader(f,d),c.attachShader(f,p),c.linkProgram(f),c.detachShader(f,d),c.detachShader(f,p),c.deleteShader(d),c.deleteShader(p),c.useProgram(f);const m=c.createBuffer();c.bindBuffer(34962,m),c.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const y=c.getAttribLocation(f,"aPosition");c.vertexAttribPointer(y,3,5126,!1,0,0),c.enableVertexAttribArray(y),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const g=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,g),c.deleteProgram(f),c.deleteBuffer(m),g.join("")}(o),i="801621810",n="8016218135",r="80162181161",a=Fs?.isIpad?[["a7",r,12],["a8",n,15],["a8x",n,15],["a9",n,15],["a9x",n,15],["a10",n,15],["a10x",n,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",r,12],["a8",n,12],["a9",n,15],["a10",n,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let l;return s==="80162181255"?l=a.filter(([,,c])=>c>=14):(l=a.filter(([,c])=>c===s),l.length||(l=a)),l.map(([c])=>`apple ${c} gpu`)}class gd extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const Ll=[],yd=[];function M0(o,e){if(o===e)return 0;const t=o;o.length>e.length&&(o=e,e=t);let s=o.length,i=e.length;for(;s>0&&o.charCodeAt(~-s)===e.charCodeAt(~-i);)s--,i--;let n,r=0;for(;r<s&&o.charCodeAt(r)===e.charCodeAt(r);)r++;if(s-=r,i-=r,s===0)return i;let a,l,c=0,h=0,u=0;for(;h<s;)yd[h]=o.charCodeAt(r+h),Ll[h]=++h;for(;u<i;)for(n=e.charCodeAt(r+u),a=u++,c=u,h=0;h<s;h++)l=n===yd[h]?a:a+1,a=Ll[h],c=Ll[h]=a>c?l>c?c+1:l:l>a?a+1:l;return c}function C0(o){return o!=null}const E0=({mobileTiers:o=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:n="https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks"}={})=>Il(void 0,void 0,void 0,function*(){const r={};if(tm)return{tier:0,type:"SSR"};const{isIpad:a=!!Fs?.isIpad,isMobile:l=!!Fs?.isMobile,screenSize:c=window.screen,loadBenchmarks:h=S=>Il(void 0,void 0,void 0,function*(){const C=yield fetch(`${n}/${S}`).then(w=>w.json());if(parseInt(C.shift().split(".")[0],10)<4)throw new gd("Detect GPU benchmark data is out of date. Please update to version 4x");return C})}=t;let{renderer:u}=t;const d=(S,C,w,R,P)=>({device:P,fps:R,gpu:w,isMobile:l,tier:S,type:C});let p,f="";if(u)u=md(u),p=[u];else{const S=s||function(w,R=!1){const P={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:R,powerPreference:"high-performance",stencil:!1};w&&delete P.powerPreference;const z=window.document.createElement("canvas"),$=z.getContext("webgl",P)||z.getContext("experimental-webgl",P);return $??void 0}(Fs?.isSafari12,i);if(!S)return d(0,"WEBGL_UNSUPPORTED");const C=Fs?.isFirefox?null:S.getExtension("WEBGL_debug_renderer_info");if(u=C?S.getParameter(C.UNMASKED_RENDERER_WEBGL):S.getParameter(S.RENDERER),!u)return d(1,"FALLBACK");f=u,u=md(u),p=function(w,R,P){return R==="apple gpu"?w0(w,R,P):[R]}(S,u,l)}const m=(yield Promise.all(p.map(function(S){var C;return Il(this,void 0,void 0,function*(){const w=(be=>{const at=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const Ot of at)if(be.includes(Ot))return Ot})(S);if(!w)return;const R=`${l?"m":"d"}-${w}${a?"-ipad":""}.json`,P=r[R]=(C=r[R])!==null&&C!==void 0?C:h(R);let z;try{z=yield P}catch(be){if(be instanceof gd)throw be;return}const $=function(be){var at;const Ot=(be=be.replace(/\([^)]+\)/,"")).match(/\d+/)||be.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(at=Ot?.join("").replace(/\W|amd/g,""))!==null&&at!==void 0?at:""}(S);let q=z.filter(([,be])=>be===$);q.length||(q=z.filter(([be])=>be.includes(S)));const j=q.length;if(j===0)return;const X=S.split(/[.,()\[\]/\s]/g).sort().filter((be,at,Ot)=>at===0||be!==Ot[at-1]).join(" ");let Z,[we,,,,ue]=j>1?q.map(be=>[be,M0(X,be[2])]).sort(([,be],[,at])=>be-at)[0][0]:q[0],ye=Number.MAX_VALUE;const{devicePixelRatio:se}=window,Me=c.width*se*c.height*se;for(const be of ue){const[at,Ot]=be,br=at*Ot,yn=Math.abs(Me-br);yn<ye&&(ye=yn,Z=be)}if(!Z)return;const[,,ze,ot]=Z;return[ye,ze,we,ot]})}))).filter(C0).sort(([S=Number.MAX_VALUE,C],[w=Number.MAX_VALUE,R])=>S===w?C-R:S-w);if(!m.length){const S=v0.find(C=>u.includes(C));return S?d(0,"BLOCKLISTED",S):d(1,"FALLBACK",`${u} (${f})`)}const[,y,g,_]=m[0];if(y===-1)return d(0,"BLOCKLISTED",g,y,_);const b=l?o:e;let T=0;for(let S=0;S<b.length;S++)y>=b[S]&&(T=S);return d(T,"BENCHMARK",g,y,_)});function sm(o){let e=0;const t=performance.now();function s(){e++;const i=performance.now();if(i-t>=100){const n=e/((i-t)/1e3),r=Math.round(n/30)*30;o(r)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function im(o=!1,e=!1){return new Promise(t=>{E0().then(s=>{let i=!1;const n=document.createElement("canvas"),r=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(i="transferControlToOffscreen"in n,r){const l=navigator.userAgent.match(/version\/(\d+)/i);i=(l?parseInt(l[1]):0)>=17}const a={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:s.isMobile!==void 0?s.isMobile:!1,supportOffScreenCanvas:i,supportWebGPU:!!navigator.gpu,quality:"Low",dev:o,editor:e};s.tier===3?a.quality="High":s.tier===2&&(a.quality="Medium"),sm(l=>{a.fps=l,t(a)})})})}function Si(o,e,t){return Math.min(e,Math.max(o,t))}function za(o,e,t){return(t-o)/(e-o)}function or(o,e,t){return o*(1-t)+e*t}function A0(o,e,t,s,i){return or(t,s,za(o,e,i))}function R0(o,e){const t=o-e;return Math.sqrt(t*t)}function is(o,e=1){return Number(o.toFixed(e))}function N0(o,e,t,s){return or(o,e,1-Math.exp(-t*s))}function P0(o,e=1){return Number(o.toFixed(e))}function F0(o,e,t,s){return o===e&&t===s}function D0(o,e,t,s){return 1/(3*e*o*o+2*t*o+s)}function O0(o,e,t,s,i){return e*(o*o*o)+t*(o*o)+s*o+i}function B0(o,e,t,s,i){const n=o*o;return e*(n*o)+t*n+s*o+i}function I0(o,e,t,s,i){if(o<=0)return 0;if(o>=1)return 1;if(F0(e,t,s,i))return o;const n=0,r=0,a=e,l=t,c=s,h=i,u=1,d=1,p=u-3*c+3*a-n,f=3*c-6*a+3*n,m=3*a-3*n,y=n,g=d-3*h+3*l-r,_=3*h-6*l+3*r,b=3*l-3*r,T=r;let S=o;for(let C=0;C<5;C++){const w=O0(S,p,f,m,y);let R=D0(S,p,f,m);R===1/0&&(R=o),S-=(w-o)*R,S=Math.min(Math.max(S,0),1)}return B0(S,g,_,b,T)}const Oo=o=>Math.round(Math.min(1,Math.max(0,o))*255).toString(16).padStart(2,"0");function L0({r:o,g:e,b:t,a:s=1}){const i=`#${Oo(o)}${Oo(e)}${Oo(t)}`;return s<1?`${i}${Oo(s)}`:i}async function U0(){for(;!document.getElementById("theatrejs-studio-root");)await new Promise(s=>setTimeout(s,100));const o=document.getElementById("theatrejs-studio-root");if(o===null||o.shadowRoot===null)return;const e=o.shadowRoot.getElementById("pointer-root");if(e===null)return;const t=e.children[0];if(t!==null){try{const i=t.children[1].children[1];i.parentElement?.removeChild(i)}catch{}try{const s=t.children[3];s.style.top="0",s.style.right="300px"}catch{}}}function k0(o,e,t,s){s.sheetObject(o,e,{transform:{position:{x:t.position.x,y:t.position.y,z:t.position.z},rotation:{x:t.rotation.x,y:t.rotation.y,z:t.rotation.z},scale:{x:t.scale.x,y:t.scale.y,z:t.scale.z},visible:t.visible}},i=>{const n=i.transform;t.position.copy(n.position),t.rotation.copy(n.rotation),t.scale.copy(n.scale),t.visible=n.visible})}const z0=["allowOverride","alphaHash","alphaTest","alphaToCoverage","blendAlpha","blendColor","blendDst","blendDstAlpha","blendEquation","blendEquationAlpha","blendSrc","blendSrcAlpha","blending","clipIntersection","clipShadows","clipping","clippingPlanes","colorWrite","combine","defaultAttributeValues","defines","depthFunc","depthTest","depthWrite","dithering","extensions","fog","forceSinglePass","fragmentShader","glslVersion","id","index0AttributeName","index1AttributeName","index2AttributeName","index3AttributeName","index4AttributeName","isMaterial","lights","linewidth","name","needsUpdate","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","precision","premultipliedAlpha","shadowSide","side","stencilFail","stencilFunc","stencilFuncMask","stencilRef","stencilWrite","stencilWriteMask","stencilZFail","stencilZPass","toneMapped","transparent","type","uniformsGroups","uniformsNeedUpdate","userData","uuid","version","vertexColors","vertexShader","visible","wireframe","wireframeLinewidth","wireframeLinecap","wireframeLinejoin"];function xd(o){const e=typeof o;if(o===null||o.isTexture)return"texture";if(e==="boolean")return"boolean";if(e==="number")return"number";if(e==="string")return"string";if(e==="object"){if(o.isColor)return"color";if(o.isVector2)return"vector2";if(o.isVector3)return"vector3";if(o.isVector4)return"vector4";if(o.isMatrix2)return"matrix2";if(o.isMatrix3)return"matrix3";if(o.isMatrix4)return"matrix4";if(o.isEuler)return"euler";if(Array.isArray(o))return"array"}return"object"}function nm(o){const e=[];for(const s in o){const i=z0.find(a=>a===s),n=s.indexOf("_")===0||s.indexOf("is")===0;if(!(i||n))if(s==="uniforms"){const a=o.uniforms;for(const l in a){const c=a[l].value,h=xd(c);h==="array"||h==="object"||e.push({name:`uniforms.${l}.value`,type:h,value:c})}}else{const a=xd(o[s]);e.push({name:s,type:a,value:o[s]})}}return e.filter(s=>s.type!=="array"&&s.type!=="object"&&s.type!=="texture")}function rm(o){const e={},t={nudgeMultiplier:.01};return o.forEach(s=>{let i=s.value;switch(s.type){case"color":i=oe.types.rgba({r:i.r,g:i.g,b:i.b,a:1});break;case"number":i=oe.types.number(i,t);break;case"euler":case"vector3":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t),z:oe.types.number(i.z,t)};break;case"vector2":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t)};break;case"vector4":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t),z:oe.types.number(i.z,t),w:oe.types.number(i.w,t)};break;case"matrix2":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t)};break;case"matrix3":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t),4:oe.types.number(i.elements[4],t),5:oe.types.number(i.elements[5],t),6:oe.types.number(i.elements[6],t),7:oe.types.number(i.elements[7],t),8:oe.types.number(i.elements[8],t)};break;case"matrix4":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t),4:oe.types.number(i.elements[4],t),5:oe.types.number(i.elements[5],t),6:oe.types.number(i.elements[6],t),7:oe.types.number(i.elements[7],t),8:oe.types.number(i.elements[8],t),9:oe.types.number(i.elements[9],t),10:oe.types.number(i.elements[10],t),11:oe.types.number(i.elements[11],t),12:oe.types.number(i.elements[12],t),13:oe.types.number(i.elements[13],t),14:oe.types.number(i.elements[14],t),15:oe.types.number(i.elements[15],t)};break}if(s.name.includes(".")){const n=s.name.split(".");let r=e;for(let a=0;a<n.length-1;a++){const l=n[a];r[l]||(r[l]={}),r=r[l]}r[n[n.length-1]]=i}else e[s.name]=i}),e}function om(o,e,t){e.forEach(s=>{if(o[s.name]!==void 0)switch(s.type){case"boolean":case"number":o[s.name]=t.material[s.name];break;case"color":case"euler":case"matrix2":case"matrix3":case"matrix4":case"vector2":case"vector3":case"vector4":o[s.name].copy(t.material[s.name]);break}})}function V0(o,e,t,s){if(!t.isMaterial)return;const i=nm(t),n=rm(i);s.sheetObject(o,e,{material:n},r=>{om(t,i,r)})}const ch=o=>{o?.dispose()},qh=o=>{if(o)if(Array.isArray(o))o.forEach(e=>qh(e));else{for(const e in o){const t=o[e];t!==null&&t instanceof x.Texture&&ch(t)}if(o.isShaderMaterial===!0){const e=o;for(const t in e.uniforms){const s=e.uniforms[t];s.value!==null&&s.value instanceof x.Texture&&ch(s.value)}}o.dispose()}},Ls=o=>{if(o){for(;o.children.length>0;){const e=o.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):Ls(e)}if(o.parent&&o.parent.remove(o),o.isMesh){const e=o;e.geometry?.dispose(),qh(e.material)}o.dispose!==void 0&&o.dispose()}};exports.totalThreeObjects=0;const hh=()=>{exports.totalThreeObjects=0},Va=o=>{if(!o)return;let e=o.name.replaceAll(" ","").replaceAll("/",".");if(e.length===0&&(e=`obj_${exports.totalThreeObjects}`,exports.totalThreeObjects++),o.parent!==null&&o.parent.uuid.length>0&&(e=`${o.parent.uuid}.${e}`),o.uuid=e,o.isMesh!==void 0){const t=o;if(Array.isArray(t.material))t.material.forEach((s,i)=>{s.uuid=`${e}.material.${i}`});else{const s=t.material;s.uuid=`${e}.material`}}o.children.forEach(t=>Va(t))};class Ni{static renderer;static canvas;static context=null;static scene=null;static camera=null;static material=null;static inited=!1;static width=100;static height=100;static init(){this.inited||(this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.context=this.canvas.getContext("2d"),this.inited=!0)}static renderToBlob(e){this.init();const t=e.repeat.clone(),s=e.offset.clone();if(e.repeat.set(1,1),e.offset.set(0,0),this.context!==null){this.context.clearRect(0,0,this.width,this.height);const i=e.image;if(i!=null&&i.width>0){this.canvas.title=e.sourceFile;const n=this.canvas.width/i.width,r=this.renderToCanvas(e);this.context.drawImage(r,0,0,i.width*n,i.height*n)}}return e.repeat.copy(t),e.offset.copy(s),this.canvas.toDataURL("image/png")}static renderToCanvas(e){if(this.material===null){this.camera=new x.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new x.Scene,this.material=new x.MeshBasicMaterial;const t=new x.BufferGeometry;t.setAttribute("position",new x.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new x.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new x.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new x.Mesh(t,this.material);this.scene.add(s)}if(e.isRenderTargetTexture)this.material.map=e,this.renderer.render(this.scene,this.camera);else{const t=this.renderer.outputColorSpace,s=e.colorSpace;this.renderer.outputColorSpace=x.LinearSRGBColorSpace,e.colorSpace=x.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function G0(o){return new Promise(e=>{const t=new x.ObjectLoader;t.parseAsync(o.scene).then(s=>{const i=new x.AnimationMixer(s);if(o.animations.length>0){const r=o.animations.map(l=>x.AnimationClip.parse(l));i.clipAction(r[0]).play(),i.getRoot().animations=o.animations,i.getRoot().mixer=i}const n=[];o.cameras&&o.cameras.length>0&&o.cameras.forEach(r=>{const a=t.parse(r);n.push(a)}),e({animations:o.animations,model:s,mixer:i,cameras:n})})})}let uh=[];function am(o,e,t=!0){Ni.renderer=e.renderer;const s=[];s.push({type:"boolean",prop:"Enabled",value:o.enabled});let i=(r,a)=>{console.log("Default Handle Pass:",r,a)};if(o.name==="EffectPass")o.effects.forEach(r=>{r.uniforms.size>0&&r.uniforms.forEach((a,l)=>{if(l==="map")return;const c=`${r.name.replace("Effect","")} ${l}`;if(a.value===null&&t)s.push({prop:l,title:c,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(a.value.isTexture&&t){const h=a.value,u=Ni.renderToBlob(h);s.push({prop:l,title:c,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:u}})}else typeof a.value=="number"?s.push({prop:l,title:c,type:"number",value:a.value,step:.01}):typeof a.value=="string"?s.push({prop:l,title:c,type:"string",value:a.value}):typeof a.value=="boolean"&&s.push({prop:l,title:c,type:"boolean",value:a.value})})}),i=(r,a)=>{o.effects.forEach(l=>{l.uniforms.size>0&&l.uniforms.forEach((c,h)=>{h===r&&(c.value=a)})})};else if(o.name==="ShaderPass"){const r=o.fullscreenMaterial;for(const a in r.uniforms){if(a==="inputBuffer"||a==="map")continue;const l=r.uniforms[a],c=`${r.name.replace("Material","")} ${a}`;if(l.value===null&&t)s.push({title:c,prop:a,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(l.value.isTexture&&t){const h=l.value,u=Ni.renderToBlob(h);s.push({title:c,prop:a,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:u}})}else typeof l.value=="number"?s.push({title:c,prop:a,type:"number",value:l.value,step:.01}):typeof l.value=="string"?s.push({title:c,prop:a,type:"string",value:l.value}):typeof l.value=="boolean"&&s.push({title:c,prop:a,type:"boolean",value:l.value})}i=(a,l)=>{const c=r.uniforms[a];c.value=l}}else return;const n=`${o.name}: ${o.scene.name}`;e.addGroup({title:n,items:s,onUpdate:(r,a)=>{r==="Enabled"?o.enabled=a:i(r,a)}}),uh.push(n)}function H0(o,e){o.passes.forEach(t=>{am(t,e)})}function W0(o){uh.forEach(e=>{o.removeGroup(e)}),uh=[]}function $0(o,e,t,s=1024){return new Promise(i=>{const n=e.aspect,r=e.fov,a=e.rotation.clone(),l=t.outputBuffer;e.aspect=1,e.fov=90,e.updateProjectionMatrix();const c=new x.WebGLRenderTarget(s,s,{format:x.RGBAFormat,depthBuffer:!0,stencilBuffer:!1});t.outputBuffer=c,bn(o,c,e,"nx",t,s).then(()=>{bn(o,c,e,"ny",t,s).then(()=>{bn(o,c,e,"nz",t,s).then(()=>{bn(o,c,e,"px",t,s).then(()=>{bn(o,c,e,"py",t,s).then(()=>{bn(o,c,e,"pz",t,s).then(()=>{e.aspect=n,e.fov=r,e.rotation.copy(a),e.updateMatrixWorld(),e.updateProjectionMatrix(),t.outputBuffer=l,c.dispose(),i()})})})})})})})}function bn(o,e,t,s,i,n){return new Promise(r=>{const a=Math.PI/2;switch(s){case"nx":t.rotation.set(0,-a,0);break;case"ny":t.rotation.set(-a,0,Math.PI);break;case"nz":t.rotation.set(0,0,0);break;case"px":t.rotation.set(0,a,0);break;case"py":t.rotation.set(a,0,Math.PI);break;case"pz":t.rotation.set(0,Math.PI,0);break}t.updateMatrixWorld(),i.render();const l=new Uint8Array(n*n*4);o.readRenderTargetPixels(e,0,0,n,n,l);const c=document.createElement("canvas");c.width=c.height=n;const h=c.getContext("2d"),u=h.createImageData(n,n);u.data.set(l),h.putImageData(u,0,0);const d=document.createElement("canvas");d.width=d.height=n;const p=d.getContext("2d");p.translate(0,n),p.scale(1,-1),p.drawImage(c,0,0);const f=d.toDataURL("image/png"),m=document.createElement("a");m.href=f,m.download=`${t.name}_${s}.png`,document.body.appendChild(m),m.click(),m.remove(),r()})}const Tn=Yh(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),j0=Yh(["clientX","clientY","deltaX","deltaY","deltaMode"]),q0=Yh(["ctrlKey","metaKey","shiftKey","keyCode"]);function Y0(o,e){o.preventDefault(),j0(o,e)}function X0(o){o.preventDefault()}function Z0(o,e,t){for(const s of e)t[s]=o[s]}function Yh(o){return function(t,s){const i={type:t.type};Z0(t,o,i),s(i)}}function Ul(o,e){const t=[],s={type:o.type,touches:t};for(let i=0;i<o.touches.length;++i){const n=o.touches[i];t.push({pageX:n.pageX,pageY:n.pageY})}e(s)}const Q0={37:!0,38:!0,39:!0,40:!0};function K0(o,e){const{keyCode:t}=o;Q0[t]&&(o.preventDefault(),q0(o,e))}const J0={contextmenu:X0,mousedown:Tn,mousemove:Tn,mouseup:Tn,pointerdown:Tn,pointermove:Tn,pointerup:Tn,touchstart:Ul,touchmove:Ul,touchend:Ul,wheel:Y0,keydown:K0};let ex=0;class tx{id;worker;constructor(e,t,s){this.id=ex++,this.worker=t;const i=r=>{this.worker.postMessage({type:"event",id:this.id,data:r})};t.postMessage({type:"makeProxy",id:this.id});for(const[r,a]of Object.entries(s))e.addEventListener(r,l=>{a(l,i)});function n(){i({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",n),n()}}class lm extends x.EventDispatcher{style={};left=0;top=0;width=0;height=0;ownerDocument=void 0;constructor(){super(),this.ownerDocument=this}get clientWidth(){return this.width}set clientWidth(e){this.width=e}get clientHeight(){return this.height}set clientHeight(e){this.height=e}setPointerCapture(){}releasePointerCapture(){}getBoundingClientRect(){return{x:this.left,y:this.top,left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height,toJSON:()=>({})}}handleEvent(e){if(e.type==="size"){this.left=e.left,this.top=e.top,this.width=e.width,this.height=e.height;return}e.preventDefault=fo,e.stopPropagation=fo,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class sx{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new lm;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}class ix{assets={audio:new Map,image:new Map,json:new Map,model:new Map,video:new Map};components=new Map;settings={dpr:1,fps:30,width:0,height:0,mobile:!1,supportOffScreenCanvas:!1,supportWebGPU:!1,quality:"Low",dev:!1,editor:!1};onUpdateCallback;playing=!1;rafID=-1;dispose(){this.pause(),this.components.forEach(e=>e.dispose()),this.components.clear()}detectSettings(e=!1,t=!1){return new Promise(s=>{im(e,t).then(i=>{this.settings=i,s()})})}update(){}draw(){}play=()=>{this.playing||(this.playing=!0,this.onUpdate())};pause=()=>{this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)};onUpdate=()=>{this.update(),this.isApp&&this.draw(),this.onUpdateCallback&&this.onUpdateCallback(),this.rafID=requestAnimationFrame(this.onUpdate)};addComponent(e,t){this.components.set(e,t)}get debugEnabled(){return this.settings.dev}get isApp(){return!this.editor}set isApp(e){this.editor=!e}get editor(){return this.settings.editor}set editor(e){this.settings.editor=e}}class Xh{name;_debug=!1;_editor=!1;broadcastChannel;constructor(e,t=!1,s=!1){this.name=e,this._debug=t,this._editor=s,t&&(this.broadcastChannel=new BroadcastChannel(e),this.broadcastChannel.addEventListener("message",this.messageHandler.bind(this)))}dispose(){this.broadcastChannel?.removeEventListener("message",this.messageHandler.bind(this)),this.broadcastChannel?.close()}get debug(){return this._debug}get editor(){return this._editor}send(e){if(this.editor&&e.target==="app"||!this.editor&&e.target==="editor")try{this.broadcastChannel?.postMessage(e)}catch(s){console.log("Hermes - Error sending message:"),console.log(s),console.log(e)}}messageHandler(e){const t=e.data;t.target==="app"?this.handleApp(t):this.handleEditor(t)}handleApp(e){}handleEditor(e){}}function nx(o,e,t,s,i){const n=1-o;return n*n*n*e+3*n*n*o*t+3*n*o*o*s+o*o*o*i}function rx(o,e,t){if(o.type!=="bezier"||o.handles.length!==4)throw new Error("Invalid keyframe data for Bézier interpolation.");const[s,i]=o.handles,n=(t-o.position)/(e.position-o.position);return nx(n,o.value,o.value+s,e.value+i,e.value)}class ox extends Xh{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;rafDriver=void 0;constructor(e=!1,t=!1){super("RemoteTheatre",e,t)}dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}loadProject(e,t,s){return this.project=oe.getProject(e,{state:s}),new Promise((i,n)=>{this.project?.ready.then(()=>{if(s){const r=s.sheetsById;for(const a in r)this.sheet(a)}t&&(this.rafDriver=oe.createRafDriver({name:e})),i()}).catch(()=>n())})}getSheetInstance(e,t){return t!==void 0?`${e}-${t}`:e}sheet(e,t){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const s=this.getSheetInstance(e,t);let i=this.sheets.get(s);return i!==void 0||(i=this.project?.sheet(e,t),this.sheets.set(s,i)),i}playSheet(e,t,s){return new Promise(i=>{const n=t!==void 0?{...t}:{};n.rafDriver=this.rafDriver,this.sheet(e,s)?.sequence.play(n).then(r=>i(r)),this.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.send({event:"pauseSheet",target:"editor",data:{sheet:e,instance:t}})}clearSheetObjects(e){this.sheetObjects.forEach((t,s)=>{s.search(`${e}_`)>-1&&this.unsubscribe(t)})}sheetObject(e,t,s,i,n){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const r=this.sheet(e,n);if(r===void 0)return;const l=`${this.getSheetInstance(e,n)}_${t}`;let c=this.sheetObjects.get(l),h=s;c!==void 0&&(h={...s,...c.value}),c=r.object(t,h,{reconfigure:!0}),this.sheetObjects.set(l,c),this.sheetObjectCBs.set(l,i!==void 0?i:fo);function u(p,f,m){if(typeof m=="object")if(em(m))p[f]={r:m.r,g:m.g,b:m.b,a:m.a};else for(const y in m){const g=m[y];typeof g=="object"&&u(m,y,g)}}const d=c.onValuesChange(p=>{const f=this.sheetObjectCBs.get(l);if(this.editor){for(const m in p){const y=p[m];typeof y=="object"&&u(p,m,y)}this.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:l,values:p}}),f&&f(p)}else f&&f(p)});return this.sheetObjectUnsubscribe.set(l,d),c}getSheetObjectKeyframes(e,t,s){const i=this.sheet(e);if(i===void 0)return[];const n=`${e}_${t}`,r=this.sheetObjects.get(n);return r===void 0?[]:i.sequence.__experimental_getKeyframes(r.props[s])}getSheetObjectVectors(e,t){const s=this.sheet(e);if(s===void 0)return[];const i=`${e}_${t}`,n=this.sheetObjects.get(i);if(n===void 0)return[];const r=[],a=s.sequence.__experimental_getKeyframes(n.props.x),l=s.sequence.__experimental_getKeyframes(n.props.y),c=s.sequence.__experimental_getKeyframes(n.props.z),h=new Set;return a.forEach(d=>h.add(d.position)),l.forEach(d=>h.add(d.position)),c.forEach(d=>h.add(d.position)),Array.from(h).sort((d,p)=>d-p).forEach(d=>{const p=(f,m)=>{const y=f.find((b,T)=>b.position<=m&&(f[T+1]?.position||1/0)>m),g=f.find(b=>b.position>m);if(!y)return g?.value||0;if(!g||y.position===m)return y.value;if(y.type==="bezier")return rx(y,g,m);const _=(m-y.position)/(g.position-y.position);return y.value+_*(g.value-y.value)};r.push({position:d,x:p(a,d),y:p(l,d),z:p(c,d)})}),r}update(e){this.rafDriver?.tick(e)}unsubscribe(e){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const t=e.address.sheetId,s=e.address.objectKey;this.sheets.get(t)?.detachObject(s);const n=`${t}_${s}`,r=this.sheetObjectUnsubscribe.get(n);r!==void 0&&(this.sheetObjects.delete(n),this.sheetObjectCBs.delete(n),this.sheetObjectUnsubscribe.delete(n),r())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet: ${e.data.sheet}`,t);break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet Object: ${e.data.sheet}, ${e.data.key}: ${e.data.sheet}_${e.data.key}`,t);break;case"updateSheetObject":t=this.sheets.get(e.data.sheet),t!==void 0&&t.sequence.pause(),t=this.sheetObjectCBs.get(e.data.sheetObject),t!==void 0?t(e.data.values):console.log(`Hermes - Can't update Sheet Object: ${e.data.sheetObject}, ${e.data.sheet}`,t);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),t!==void 0?t.sequence.position=e.data.position:console.log(`Hermes - Can't update sheet position: ${e.data.sheet}, ${e.data.position}`);break}}handleEditor(e){switch(e.event){case"playSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.play(e.data.value);break;case"pauseSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.pause();break}}getSheetNames(){const e=[];return this.sheets.forEach((t,s)=>{e.push(s)}),e}handleEditorApp(){if(this.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(i=>{i.length<1||i.forEach(n=>{let r=n.address.sheetId,a="setSheet",l={};switch(n.type){case"Theatre_Sheet_PublicAPI":a="setSheet",l={sheet:n.address.sheetId},this.activeSheet=this.sheets.get(n.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":a="setSheetObject",r+=`_${n.address.objectKey}`,l={id:r,sheet:n.address.sheetId,key:n.address.objectKey},this.activeSheet=this.sheets.get(n.address.sheetId);break}this.send({event:a,target:"app",data:l})})});let e=-1;const t=()=>{if(this.activeSheet!==void 0&&e!==this.activeSheet.sequence.position){e=this.activeSheet.sequence.position;const i=this.activeSheet;this.send({event:"updateTimeline",target:"app",data:{position:e,sheet:i.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function ax(o){if(o.name==="cameras")return"camera";if(o.name==="interactive")return"interactive";if(o.name==="lights")return"light";if(o.name==="ui")return"ui";if(o.name==="utils")return"utils";const e=o.type;return e.search("Helper")>-1?"icon_utils":e.search("Camera")>-1?"camera":e.search("Light")>-1?"light":"obj3D"}function Wn(o){const e={name:o.name,type:o.type,uuid:o.uuid,children:[]};return o.children.forEach(t=>{e.children.push(Wn(t))}),e}function lx(o){const e={};for(const t in o){const s=o[t].value;e[t]={value:s},s===null?e[t].value={src:"",offset:[0,0],repeat:[1,1]}:s!==void 0&&s.isTexture&&(e[t].value={src:s.image.src,offset:[s.offset.x,s.offset.y],repeat:[s.repeat.x,s.repeat.y]})}return e}function cx(o){switch(o){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function Sn(o){const e={};for(const t in o){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||cx(t))continue;const s=typeof o[t],i=o[t];switch(s){case"boolean":case"number":case"string":e[t]=i;break;case"object":i!==null?(e[t]=i,i.isTexture?e[t]={src:Ni.renderToBlob(i),offset:[i.offset.x,i.offset.y],repeat:[i.repeat.x,i.repeat.y]}:t==="uniforms"&&(e[t]=lx(e[t]))):t==="glslVersion"?e[t]="":e[t]={src:"",offset:[0,0],repeat:[1,1]};break}}return o.anisotropy!==void 0&&(e.anisotropy=o.anisotropy),o.clearcoat!==void 0&&(e.clearcoat=o.clearcoat),o.iridescence!==void 0&&(e.iridescence=o.iridescence),o.dispersion!==void 0&&(e.dispersion=o.dispersion),o.sheen!==void 0&&(e.sheen=o.sheen),o.transmission!==void 0&&(e.transmission=o.transmission),o.transmission!==void 0&&(e.transmission=o.transmission),e}function kl(o){o.updateMatrix();const e={name:o.name,type:o.type,uuid:o.uuid,visible:o.visible,matrix:o.matrix.elements,animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};o.animations.forEach(s=>{e.animations.push({name:s.name,duration:s.duration,blendMode:s.blendMode})});const t=o.type.toLowerCase();if(t.search("mesh")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Sn(n))}),e.material=i}else e.material=Sn(s.material)}else if(t.search("points")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Sn(n))}),e.material=i}else e.material=Sn(s.material)}else if(t.search("line")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(Sn(n))}),e.material=i}else e.material=Sn(s.material)}else t.search("camera")>-1?o.type==="PerspectiveCamera"?e.perspectiveCameraInfo={fov:o.fov,zoom:o.zoom,near:o.near,far:o.far,focus:o.focus,aspect:o.aspect,filmGauge:o.filmGauge,filmOffset:o.filmOffset}:o.type==="OrthographicCamera"&&(e.orthographicCameraInfo={zoom:o.zoom,near:o.near,far:o.far,left:o.left,right:o.right,top:o.top,bottom:o.bottom}):t.search("light")>-1&&(e.lightInfo={color:o.color,intensity:o.intensity,decay:o.decay,distance:o.distance,angle:o.angle,penumbra:o.penumbra,groundColor:o.groundColor,width:o.width,height:o.height});return e}function hx(o,e){const t=e.split(".");switch(t.length){case 1:return o[t[0]];case 2:return o[t[0]][t[1]];case 3:return o[t[0]][t[1]][t[2]];case 4:return o[t[0]][t[1]][t[2]][t[3]];case 5:return o[t[0]][t[1]][t[2]][t[3]][t[4]];case 6:return o[t[0]][t[1]][t[2]][t[3]][t[4]][t[5]]}}function ux(o,e){for(const t in e)o[t]=e[t]}function Ye(o,e,t){if(o===void 0){console.log(`Hermes - Can't set props: ${e}`,t);return}const s=e.split("."),i=s.length;if(typeof t!="object")switch(i){case 1:o[s[0]]=t;break;case 2:o[s[0]][s[1]]=t;break;case 3:o[s[0]][s[1]][s[2]]=t;break;case 4:o[s[0]][s[1]][s[2]][s[3]]=t;break;case 5:o[s[0]][s[1]][s[2]][s[3]][s[4]]=t;break}else{let r;switch(i){case 1:r=o[s[0]];break;case 2:r=o[s[0]][s[1]];break;case 3:r=o[s[0]][s[1]][s[2]];break;case 4:r=o[s[0]][s[1]][s[2]][s[3]];break;case 5:r=o[s[0]][s[1]][s[2]][s[3]][s[4]];break}r!=null?ux(r,t):console.log(`Hermes - Can't set props because target isn't found: ${e}`,t)}}function cm(o){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const i=new x.Texture(s);i.wrapS=x.RepeatWrapping,i.wrapT=x.RepeatWrapping,i.needsUpdate=!0,e(i)},s.onerror=t,s.src=o})}var de=(o=>(o.CUSTOM="ToolEvents::custom",o.SELECT_DROPDOWN="ToolEvents::selectDropdown",o.DRAG_UPDATE="ToolEvents::dragUpdate",o.ADD_SCENE="ToolEvents::addScene",o.REFRESH_SCENE="ToolEvents::refreshScene",o.REMOVE_SCENE="ToolEvents::removeScene",o.SET_SCENE="ToolEvents::setScene",o.SET_OBJECT="ToolEvents::setObject",o.CLEAR_OBJECT="ToolEvents::clearObject",o.ADD_CAMERA="ToolEvents::addCamera",o.REMOVE_CAMERA="ToolEvents::removeCamera",o.ADD_GROUP="ToolEvents::addGroup",o.REMOVE_GROUP="ToolEvents::removeGroup",o.ADD_SPLINE="ToolEvents::addSpline",o.ADD_RENDERER="ToolEvents::addRenderer",o.UPDATE_RENDERER="ToolEvents::updateRenderer",o))(de||{});class dx extends Xh{name;canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;renderTargetsResize=new Map;groups=new Map;_listeners={};constructor(e,t=!1,s=!1){super("RemoteThree",t,s),this.name=e}dispose(){this.scenes.forEach(e=>{Ls(e)}),this.scenes.clear(),this.scene&&Ls(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){const i={...e,target:this},n=s.slice(0);for(let r=0,a=n.length;r<a;r++)n[r].call(this,i)}}getObjectByUUID(e){const t=e.split(".")[0],s=this.scenes.get(t);if(s!==void 0)return s.getObjectByProperty("uuid",e)}getObject(e){if(!this.debug)return;this.renderer!==void 0&&(Ni.renderer=this.renderer);const t=this.getObjectByUUID(e);t&&this.setObject(t)}setObject(e){this.renderer!==void 0&&(Ni.renderer=this.renderer);const t=kl(e);this.dispatchEvent({type:"ToolEvents::setObject",value:t})}requestMethod(e,t,s,i){const n=this.getObjectByUUID(e);if(n)try{i!==void 0?hx(n,i)[t](s):n[t](s)}catch(r){console.log("Hermes - Error requesting method:",e,t,s),console.log(r)}}updateObject(e,t,s){this.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}onUpdateObject(e,t,s){const i=this.getObjectByUUID(e);i&&Ye(i,t,s)}onCreateTexture(e,t,s){const i=this.getObjectByUUID(e);if(i){const n=r=>{const a=t.split(".");switch(a.length){case 1:i[a[0]]=r;break;case 2:i[a[0]][a[1]]=r;break;case 3:i[a[0]][a[1]][a[2]]=r;break;case 4:i[a[0]][a[1]][a[2]][a[3]]=r;break;case 5:i[a[0]][a[1]][a[2]][a[3]][a[4]]=r;break}i.material.needsUpdate=!0};s.src.length>0?cm(s.src).then(r=>{r.offset.set(s.offset[0],s.offset[1]),r.repeat.set(s.repeat[0],s.repeat[1]),n(r)}):n(null)}}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}addSpline(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.debug)return;const s=`#${e.getClearColor(new x.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:e.autoClear,autoClearColor:e.autoClearColor,autoClearDepth:e.autoClearDepth,autoClearStencil:e.autoClearStencil,outputColorSpace:e.outputColorSpace,localClippingEnabled:e.localClippingEnabled,clearColor:s,clearAlpha:e.getClearAlpha(),colorManagement:x.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure,type:e.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}updateRenderer(e){this.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.debug))return;hh(),Va(e);const t=Wn(e);this.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.debug)return;const t=this.scenes.get(e);if(t!==void 0){const s=Wn(t);this.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.debug))return;const t=Wn(e);this.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scene!==void 0&&this.scene.uuid.search(e)>-1?this.scene:(this.scenes.forEach((s,i)=>{e.search(i)>-1&&(t=s)}),t)}setScene(e){if(e===void 0||(this.scene=e,!this.debug))return;this.renderer!==void 0&&(Ni.renderer=this.renderer),hh(),Va(e);const t=Wn(e);this.send({event:"setScene",target:"editor",data:t})}requestSize(){this.send({event:"requestSize",target:"app"})}addCamera(e){if(!this.debug)return;const t=kl(e);this.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.debug)return;const t=kl(e);this.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"refreshScene":this.send({event:"refreshScene",target:"editor",data:Wn(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.outputColorSpace=e.data.outputColorSpace,this.renderer.localClippingEnabled=e.data.localClippingEnabled,this.renderer.setClearColor(e.data.clearColor,e.data.clearAlpha),this.renderer.toneMapping=e.data.toneMapping,this.renderer.toneMappingExposure=e.data.toneMappingExposure,x.ColorManagement.enabled=e.data.colorManagement);break}if(e.event==="updateGroup"){const t=JSON.parse(e.data);this.groups.get(t.group)?.onUpdate(t.prop,t.value)}}handleEditor(e){switch(e.event){case"addScene":this.dispatchEvent({type:"ToolEvents::addScene",value:e.data});break;case"refreshScene":this.dispatchEvent({type:"ToolEvents::refreshScene",value:e.data});break;case"removeScene":this.dispatchEvent({type:"ToolEvents::removeScene",value:e.data});break;case"setScene":this.dispatchEvent({type:"ToolEvents::setScene",value:e.data});break;case"addCamera":this.dispatchEvent({type:"ToolEvents::addCamera",value:e.data});break;case"removeCamera":this.dispatchEvent({type:"ToolEvents::removeCamera",value:e.data});break;case"addGroup":this.dispatchEvent({type:"ToolEvents::addGroup",value:e.data});break;case"removeGroup":this.dispatchEvent({type:"ToolEvents::removeGroup",value:e.data});break;case"addSpline":this.dispatchEvent({type:"ToolEvents::addSpline",value:e.data});break;case"addRenderer":this.dispatchEvent({type:"ToolEvents::addRenderer",value:e.data})}}messageHandler(e){const t=e.data;if(t.event==="updateObject"){this.onUpdateObject(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="createTexture"){this.onCreateTexture(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="requestSize"){t.target==="app"?this.send({event:"requestSize",target:"editor",data:{width:this.width,height:this.height}}):this.scenes.forEach(s=>{s.resize!==void 0&&s.resize(t.data.width,t.data.height)});return}t.target==="app"?this.handleApp(t):this.handleEditor(t)}addRT(e,t=!0,s){const i=new x.WebGLRenderTarget(32,32,s);i.texture.name=e,this.renderTargets.set(e,i),this.renderTargetsResize.set(e,t)}removeRT(e){this.renderTargets.delete(e),this.renderTargetsResize.delete(e)}resize(e,t){const s=this.dpr;this.renderTargets.forEach((n,r)=>{this.renderTargetsResize.get(r)&&n.setSize(e*s,t*s)});const i=!(this.renderer?.domElement instanceof OffscreenCanvas);this.renderer?.setSize(e,t,i)}set dpr(e){this.renderer?.setPixelRatio(Si(1,2,e))}get dpr(){return this.renderer!==void 0?this.renderer?.getPixelRatio():1}get width(){return this.renderer!==void 0?this.renderer.domElement.width/this.dpr:0}get height(){return this.renderer!==void 0?this.renderer.domElement.height/this.dpr:0}}var Bo={exports:{}},Sr={};/**
|
|
18
|
+
`,d=c.createShader(35633),p=c.createShader(35632),f=c.createProgram();if(!(p&&d&&f))return;c.shaderSource(d,h),c.shaderSource(p,u),c.compileShader(d),c.compileShader(p),c.attachShader(f,d),c.attachShader(f,p),c.linkProgram(f),c.detachShader(f,d),c.detachShader(f,p),c.deleteShader(d),c.deleteShader(p),c.useProgram(f);const m=c.createBuffer();c.bindBuffer(34962,m),c.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const x=c.getAttribLocation(f,"aPosition");c.vertexAttribPointer(x,3,5126,!1,0,0),c.enableVertexAttribArray(x),c.clearColor(1,1,1,1),c.clear(16384),c.viewport(0,0,1,1),c.drawArrays(4,0,3);const g=new Uint8Array(4);return c.readPixels(0,0,1,1,6408,5121,g),c.deleteProgram(f),c.deleteBuffer(m),g.join("")}(o),i="801621810",n="8016218135",r="80162181161",a=Fs?.isIpad?[["a7",r,12],["a8",n,15],["a8x",n,15],["a9",n,15],["a9x",n,15],["a10",n,15],["a10x",n,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",r,12],["a8",n,12],["a9",n,15],["a10",n,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let l;return s==="80162181255"?l=a.filter(([,,c])=>c>=14):(l=a.filter(([,c])=>c===s),l.length||(l=a)),l.map(([c])=>`apple ${c} gpu`)}class _d extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const zl=[],bd=[];function I0(o,e){if(o===e)return 0;const t=o;o.length>e.length&&(o=e,e=t);let s=o.length,i=e.length;for(;s>0&&o.charCodeAt(~-s)===e.charCodeAt(~-i);)s--,i--;let n,r=0;for(;r<s&&o.charCodeAt(r)===e.charCodeAt(r);)r++;if(s-=r,i-=r,s===0)return i;let a,l,c=0,h=0,u=0;for(;h<s;)bd[h]=o.charCodeAt(r+h),zl[h]=++h;for(;u<i;)for(n=e.charCodeAt(r+u),a=u++,c=u,h=0;h<s;h++)l=n===bd[h]?a:a+1,a=zl[h],c=zl[h]=a>c?l>c?c+1:l:l>a?a+1:l;return c}function L0(o){return o!=null}const U0=({mobileTiers:o=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:s,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:n="https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks"}={})=>kl(void 0,void 0,void 0,function*(){const r={};if(nm)return{tier:0,type:"SSR"};const{isIpad:a=!!Fs?.isIpad,isMobile:l=!!Fs?.isMobile,screenSize:c=window.screen,loadBenchmarks:h=S=>kl(void 0,void 0,void 0,function*(){const C=yield fetch(`${n}/${S}`).then(w=>w.json());if(parseInt(C.shift().split(".")[0],10)<4)throw new _d("Detect GPU benchmark data is out of date. Please update to version 4x");return C})}=t;let{renderer:u}=t;const d=(S,C,w,R,P)=>({device:P,fps:R,gpu:w,isMobile:l,tier:S,type:C});let p,f="";if(u)u=xd(u),p=[u];else{const S=s||function(w,R=!1){const P={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:R,powerPreference:"high-performance",stencil:!1};w&&delete P.powerPreference;const z=window.document.createElement("canvas"),$=z.getContext("webgl",P)||z.getContext("experimental-webgl",P);return $??void 0}(Fs?.isSafari12,i);if(!S)return d(0,"WEBGL_UNSUPPORTED");const C=Fs?.isFirefox?null:S.getExtension("WEBGL_debug_renderer_info");if(u=C?S.getParameter(C.UNMASKED_RENDERER_WEBGL):S.getParameter(S.RENDERER),!u)return d(1,"FALLBACK");f=u,u=xd(u),p=function(w,R,P){return R==="apple gpu"?B0(w,R,P):[R]}(S,u,l)}const m=(yield Promise.all(p.map(function(S){var C;return kl(this,void 0,void 0,function*(){const w=(be=>{const at=l?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const Ot of at)if(be.includes(Ot))return Ot})(S);if(!w)return;const R=`${l?"m":"d"}-${w}${a?"-ipad":""}.json`,P=r[R]=(C=r[R])!==null&&C!==void 0?C:h(R);let z;try{z=yield P}catch(be){if(be instanceof _d)throw be;return}const $=function(be){var at;const Ot=(be=be.replace(/\([^)]+\)/,"")).match(/\d+/)||be.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(at=Ot?.join("").replace(/\W|amd/g,""))!==null&&at!==void 0?at:""}(S);let q=z.filter(([,be])=>be===$);q.length||(q=z.filter(([be])=>be.includes(S)));const j=q.length;if(j===0)return;const X=S.split(/[.,()\[\]/\s]/g).sort().filter((be,at,Ot)=>at===0||be!==Ot[at-1]).join(" ");let Z,[we,,,,de]=j>1?q.map(be=>[be,I0(X,be[2])]).sort(([,be],[,at])=>be-at)[0][0]:q[0],ye=Number.MAX_VALUE;const{devicePixelRatio:se}=window,Me=c.width*se*c.height*se;for(const be of de){const[at,Ot]=be,Sr=at*Ot,yn=Math.abs(Me-Sr);yn<ye&&(ye=yn,Z=be)}if(!Z)return;const[,,ze,ot]=Z;return[ye,ze,we,ot]})}))).filter(L0).sort(([S=Number.MAX_VALUE,C],[w=Number.MAX_VALUE,R])=>S===w?C-R:S-w);if(!m.length){const S=O0.find(C=>u.includes(C));return S?d(0,"BLOCKLISTED",S):d(1,"FALLBACK",`${u} (${f})`)}const[,x,g,_]=m[0];if(x===-1)return d(0,"BLOCKLISTED",g,x,_);const b=l?o:e;let T=0;for(let S=0;S<b.length;S++)x>=b[S]&&(T=S);return d(T,"BENCHMARK",g,x,_)});function rm(o){let e=0;const t=performance.now();function s(){e++;const i=performance.now();if(i-t>=100){const n=e/((i-t)/1e3),r=Math.round(n/30)*30;o(r)}else requestAnimationFrame(s)}requestAnimationFrame(s)}function om(o=!1,e=!1){return new Promise(t=>{U0().then(s=>{let i=!1;const n=document.createElement("canvas"),r=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(i="transferControlToOffscreen"in n,r){const l=navigator.userAgent.match(/version\/(\d+)/i);i=(l?parseInt(l[1]):0)>=17}const a={dpr:devicePixelRatio,fps:30,width:innerWidth,height:innerHeight,mobile:s.isMobile!==void 0?s.isMobile:!1,supportOffScreenCanvas:i,supportWebGPU:!!navigator.gpu,quality:"Low",dev:o,editor:e};s.tier===3?a.quality="High":s.tier===2&&(a.quality="Medium"),rm(l=>{a.fps=l,t(a)})})})}function Si(o,e,t){return Math.min(e,Math.max(o,t))}function Va(o,e,t){return(t-o)/(e-o)}function lr(o,e,t){return o*(1-t)+e*t}function k0(o,e,t,s,i){return lr(t,s,Va(o,e,i))}function z0(o,e){const t=o-e;return Math.sqrt(t*t)}function G0(o,e,t,s){return lr(o,e,1-Math.exp(-t*s))}function is(o,e=1){return Number(o.toFixed(e))}function V0(o,e,t,s){return Math.atan2(s-e,t-o)}function H0(o,e,t,s){return o===e&&t===s}function W0(o,e,t,s){return 1/(3*e*o*o+2*t*o+s)}function $0(o,e,t,s,i){return e*(o*o*o)+t*(o*o)+s*o+i}function j0(o,e,t,s,i){const n=o*o;return e*(n*o)+t*n+s*o+i}function q0(o,e,t,s,i){if(o<=0)return 0;if(o>=1)return 1;if(H0(e,t,s,i))return o;const n=0,r=0,a=e,l=t,c=s,h=i,u=1,d=1,p=u-3*c+3*a-n,f=3*c-6*a+3*n,m=3*a-3*n,x=n,g=d-3*h+3*l-r,_=3*h-6*l+3*r,b=3*l-3*r,T=r;let S=o;for(let C=0;C<5;C++){const w=$0(S,p,f,m,x);let R=W0(S,p,f,m);R===1/0&&(R=o),S-=(w-o)*R,S=Math.min(Math.max(S,0),1)}return j0(S,g,_,b,T)}const Bo=o=>Math.round(Math.min(1,Math.max(0,o))*255).toString(16).padStart(2,"0");function Y0({r:o,g:e,b:t,a:s=1}){const i=`#${Bo(o)}${Bo(e)}${Bo(t)}`;return s<1?`${i}${Bo(s)}`:i}let bn;function X0(){const[o,e]=W.useState(bn);return W.useEffect(()=>{bn||import("@theatre/studio").then(t=>{bn=t.default,bn.initialize(),bn.ui.hide(),e(bn)})},[]),o}async function Z0(){for(;!document.getElementById("theatrejs-studio-root");)await new Promise(s=>setTimeout(s,100));const o=document.getElementById("theatrejs-studio-root");if(o===null||o.shadowRoot===null)return;const e=o.shadowRoot.getElementById("pointer-root");if(e===null)return;const t=e.children[0];if(t!==null){try{const i=t.children[1].children[1];i.parentElement?.removeChild(i)}catch{}try{const s=t.children[3];s.style.top="0",s.style.right="300px"}catch{}}}function K0(o,e,t,s){s.sheetObject(o,e,{transform:{position:{x:t.position.x,y:t.position.y,z:t.position.z},rotation:{x:t.rotation.x,y:t.rotation.y,z:t.rotation.z},scale:{x:t.scale.x,y:t.scale.y,z:t.scale.z},visible:t.visible}},i=>{const n=i.transform;t.position.copy(n.position),t.rotation.copy(n.rotation),t.scale.copy(n.scale),t.visible=n.visible})}const Q0=["allowOverride","alphaHash","alphaTest","alphaToCoverage","blendAlpha","blendColor","blendDst","blendDstAlpha","blendEquation","blendEquationAlpha","blendSrc","blendSrcAlpha","blending","clipIntersection","clipShadows","clipping","clippingPlanes","colorWrite","combine","defaultAttributeValues","defines","depthFunc","depthTest","depthWrite","dithering","extensions","fog","forceSinglePass","fragmentShader","glslVersion","id","index0AttributeName","index1AttributeName","index2AttributeName","index3AttributeName","index4AttributeName","isMaterial","lights","linewidth","name","needsUpdate","polygonOffset","polygonOffsetFactor","polygonOffsetUnits","precision","premultipliedAlpha","shadowSide","side","stencilFail","stencilFunc","stencilFuncMask","stencilRef","stencilWrite","stencilWriteMask","stencilZFail","stencilZPass","toneMapped","transparent","type","uniformsGroups","uniformsNeedUpdate","userData","uuid","version","vertexColors","vertexShader","visible","wireframe","wireframeLinewidth","wireframeLinecap","wireframeLinejoin"];function Td(o){const e=typeof o;if(o===null||o.isTexture)return"texture";if(e==="boolean")return"boolean";if(e==="number")return"number";if(e==="string")return"string";if(e==="object"){if(o.isColor)return"color";if(o.isVector2)return"vector2";if(o.isVector3)return"vector3";if(o.isVector4)return"vector4";if(o.isMatrix2)return"matrix2";if(o.isMatrix3)return"matrix3";if(o.isMatrix4)return"matrix4";if(o.isEuler)return"euler";if(Array.isArray(o))return"array"}return"object"}function am(o){const e=[];for(const s in o){const i=Q0.find(a=>a===s),n=s.indexOf("_")===0||s.indexOf("is")===0;if(!(i||n))if(s==="uniforms"){const a=o.uniforms;for(const l in a){const c=a[l].value,h=Td(c);h==="array"||h==="object"||e.push({name:`uniforms.${l}.value`,type:h,value:c})}}else{const a=Td(o[s]);e.push({name:s,type:a,value:o[s]})}}return e.filter(s=>s.type!=="array"&&s.type!=="object"&&s.type!=="texture")}function lm(o){const e={},t={nudgeMultiplier:.01};return o.forEach(s=>{let i=s.value;switch(s.type){case"color":i=oe.types.rgba({r:i.r,g:i.g,b:i.b,a:1});break;case"number":i=oe.types.number(i,t);break;case"euler":case"vector3":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t),z:oe.types.number(i.z,t)};break;case"vector2":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t)};break;case"vector4":i={x:oe.types.number(i.x,t),y:oe.types.number(i.y,t),z:oe.types.number(i.z,t),w:oe.types.number(i.w,t)};break;case"matrix2":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t)};break;case"matrix3":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t),4:oe.types.number(i.elements[4],t),5:oe.types.number(i.elements[5],t),6:oe.types.number(i.elements[6],t),7:oe.types.number(i.elements[7],t),8:oe.types.number(i.elements[8],t)};break;case"matrix4":i={0:oe.types.number(i.elements[0],t),1:oe.types.number(i.elements[1],t),2:oe.types.number(i.elements[2],t),3:oe.types.number(i.elements[3],t),4:oe.types.number(i.elements[4],t),5:oe.types.number(i.elements[5],t),6:oe.types.number(i.elements[6],t),7:oe.types.number(i.elements[7],t),8:oe.types.number(i.elements[8],t),9:oe.types.number(i.elements[9],t),10:oe.types.number(i.elements[10],t),11:oe.types.number(i.elements[11],t),12:oe.types.number(i.elements[12],t),13:oe.types.number(i.elements[13],t),14:oe.types.number(i.elements[14],t),15:oe.types.number(i.elements[15],t)};break}if(s.name.includes(".")){const n=s.name.split(".");let r=e;for(let a=0;a<n.length-1;a++){const l=n[a];r[l]||(r[l]={}),r=r[l]}r[n[n.length-1]]=i}else e[s.name]=i}),e}function cm(o,e,t){e.forEach(s=>{if(o[s.name]!==void 0)switch(s.type){case"boolean":case"number":o[s.name]=t.material[s.name];break;case"color":case"euler":case"matrix2":case"matrix3":case"matrix4":case"vector2":case"vector3":case"vector4":o[s.name].copy(t.material[s.name]);break}})}function J0(o,e,t,s){if(!t.isMaterial)return;const i=am(t),n=lm(i);s.sheetObject(o,e,{material:n},r=>{cm(t,i,r)})}const ul=new y.BufferGeometry;ul.setAttribute("position",new y.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3));ul.setAttribute("normal",new y.Float32BufferAttribute([0,0,1,0,0,1],3));ul.setAttribute("uv",new y.Float32BufferAttribute([0,0,2,0,0,2],2));const ex=new y.OrthographicCamera(-.5,.5,.5,-.5,0,100),dh=o=>{o?.dispose()},Xh=o=>{if(o)if(Array.isArray(o))o.forEach(e=>Xh(e));else{for(const e in o){const t=o[e];t!==null&&t instanceof y.Texture&&dh(t)}if(o.isShaderMaterial===!0){const e=o;for(const t in e.uniforms){const s=e.uniforms[t];s.value!==null&&s.value instanceof y.Texture&&dh(s.value)}}o.dispose()}},Ls=o=>{if(o){for(;o.children.length>0;){const e=o.children[0];e.type==="Audio"?(e.pause(),e.parent&&e.parent.remove(e)):Ls(e)}if(o.parent&&o.parent.remove(o),o.isMesh){const e=o;e.geometry?.dispose(),Xh(e.material)}o.dispose!==void 0&&o.dispose()}};exports.totalThreeObjects=0;const ph=()=>{exports.totalThreeObjects=0},Ha=o=>{if(!o)return;let e=o.name.replaceAll(" ","").replaceAll("/",".");if(e.length===0&&(e=`obj_${exports.totalThreeObjects}`,exports.totalThreeObjects++),o.parent!==null&&o.parent.uuid.length>0&&(e=`${o.parent.uuid}.${e}`),o.uuid=e,o.isMesh!==void 0){const t=o;if(Array.isArray(t.material))t.material.forEach((s,i)=>{s.uuid=`${e}.material.${i}`});else{const s=t.material;s.uuid=`${e}.material`}}o.children.forEach(t=>Ha(t))};class Ni{static renderer;static canvas;static context=null;static scene=null;static camera=null;static material=null;static inited=!1;static width=100;static height=100;static init(){this.inited||(this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.context=this.canvas.getContext("2d"),this.inited=!0)}static renderToBlob(e){this.init();const t=e.repeat.clone(),s=e.offset.clone();if(e.repeat.set(1,1),e.offset.set(0,0),this.context!==null){this.context.clearRect(0,0,this.width,this.height);const i=e.image;if(i!=null&&i.width>0){this.canvas.title=e.sourceFile;const n=this.canvas.width/i.width,r=this.renderToCanvas(e);this.context.drawImage(r,0,0,i.width*n,i.height*n)}}return e.repeat.copy(t),e.offset.copy(s),this.canvas.toDataURL("image/png")}static renderToCanvas(e){if(this.material===null){this.camera=new y.OrthographicCamera(-.5,.5,.5,-.5,0,100),this.scene=new y.Scene,this.material=new y.MeshBasicMaterial;const t=new y.BufferGeometry;t.setAttribute("position",new y.Float32BufferAttribute([-.5,-.5,0,1.5,-.5,0,-.5,1.5,0],3)),t.setAttribute("normal",new y.Float32BufferAttribute([0,0,1,0,0,1],3)),t.setAttribute("uv",new y.Float32BufferAttribute([0,0,2,0,0,2],2));const s=new y.Mesh(t,this.material);this.scene.add(s)}if(e.isRenderTargetTexture)this.material.map=e,this.renderer.render(this.scene,this.camera);else{const t=this.renderer.outputColorSpace,s=e.colorSpace;this.renderer.outputColorSpace=y.LinearSRGBColorSpace,e.colorSpace=y.LinearSRGBColorSpace,this.material.map=e,this.renderer.render(this.scene,this.camera),this.renderer.outputColorSpace=t,e.colorSpace=s}return this.renderer.domElement}}function tx(o){return new Promise(e=>{const t=new y.ObjectLoader;t.parseAsync(o.scene).then(s=>{const i=new y.AnimationMixer(s);if(o.animations.length>0){const r=o.animations.map(l=>y.AnimationClip.parse(l));i.clipAction(r[0]).play(),i.getRoot().animations=o.animations,i.getRoot().mixer=i}const n=[];o.cameras&&o.cameras.length>0&&o.cameras.forEach(r=>{const a=t.parse(r);n.push(a)}),e({animations:o.animations,model:s,mixer:i,cameras:n})})})}const sx=(o,e,t,s)=>{o.setRenderTarget(s),o.clear(),o.render(e,t)};function hm(o,e,t,s){o.applyMatrix4(new y.Matrix4().makeTranslation(e,-t,-s))}function ix(o){o.computeBoundingBox();const e=o.boundingBox,t=(e.max.x-e.min.x)/2,s=(e.max.y-e.min.y)/2;hm(o,t,s,0)}function nx(o,e,t){o.left=e/-2,o.right=e/2,o.top=t/2,o.bottom=t/-2,o.position.x=e/2,o.position.y=t/-2,o.updateProjectionMatrix()}function rx(o,e,t){const s=1.7777777777777777,i=e/t;let n=e,r=t;i>s?n=t*s:r=e/s,o.left=n/-2,o.right=n/2,o.top=r/2,o.bottom=r/-2,o.updateProjectionMatrix()}function ox(){let e="transferControlToOffscreen"in document.createElement("canvas");if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){const s=navigator.userAgent.match(/version\/(\d+)/i);e=(s?parseInt(s[1]):0)>=17}return e}function ax(o,e,t=!0,s=!1){o.renderOrder=-e;const i=o.material;Array.isArray(i)?i.forEach(n=>{n.colorWrite=t,n.depthWrite=s,n.stencilWrite=!0,n.stencilRef=e,n.stencilFunc=y.AlwaysStencilFunc,n.stencilFail=y.ReplaceStencilOp,n.stencilZFail=y.ReplaceStencilOp,n.stencilZPass=y.ReplaceStencilOp}):(i.colorWrite=t,i.depthWrite=s,i.stencilWrite=!0,i.stencilRef=e,i.stencilFunc=y.AlwaysStencilFunc,i.stencilFail=y.ReplaceStencilOp,i.stencilZFail=y.ReplaceStencilOp,i.stencilZPass=y.ReplaceStencilOp)}function lx(o,e,t=!1){const s=o.material;Array.isArray(s)?s.forEach(i=>{i.stencilWrite=!0,i.stencilRef=e,i.stencilFunc=t?y.NotEqualStencilFunc:y.EqualStencilFunc,i.stencilFail=y.KeepStencilOp,i.stencilZFail=y.KeepStencilOp,i.stencilZPass=y.KeepStencilOp}):(s.stencilWrite=!0,s.stencilRef=e,s.stencilFunc=t?y.NotEqualStencilFunc:y.EqualStencilFunc,s.stencilFail=y.KeepStencilOp,s.stencilZFail=y.KeepStencilOp,s.stencilZPass=y.KeepStencilOp)}function cx(o){o.blending=y.NormalBlending,o.blendEquation=y.AddEquation,o.blendSrc=y.SrcAlphaFactor,o.blendDst=y.OneMinusSrcAlphaFactor,o.needsUpdate=!0}function hx(o){o.blending=y.CustomBlending,o.blendEquation=y.AddEquation,o.blendSrc=y.SrcAlphaFactor,o.blendDst=y.OneFactor,o.needsUpdate=!0}function ux(o){o.blending=y.CustomBlending,o.blendEquation=y.AddEquation,o.blendSrc=y.DstColorFactor,o.blendDst=y.OneMinusSrcAlphaFactor,o.needsUpdate=!0}function dx(o){o.blending=y.CustomBlending,o.blendEquation=y.AddEquation,o.blendSrc=y.OneMinusDstColorFactor,o.blendDst=y.OneFactor,o.needsUpdate=!0}let fh=[];function um(o,e,t=!0){Ni.renderer=e.renderer;const s=[];s.push({type:"boolean",prop:"Enabled",value:o.enabled});let i=(r,a)=>{console.log("Default Handle Pass:",r,a)};if(o.name==="EffectPass")o.effects.forEach(r=>{r.uniforms.size>0&&r.uniforms.forEach((a,l)=>{if(l==="map")return;const c=`${r.name.replace("Effect","")} ${l}`;if(a.value===null&&t)s.push({prop:l,title:c,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(a.value.isTexture&&t){const h=a.value,u=Ni.renderToBlob(h);s.push({prop:l,title:c,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:u}})}else typeof a.value=="number"?s.push({prop:l,title:c,type:"number",value:a.value,step:.01}):typeof a.value=="string"?s.push({prop:l,title:c,type:"string",value:a.value}):typeof a.value=="boolean"&&s.push({prop:l,title:c,type:"boolean",value:a.value})})}),i=(r,a)=>{o.effects.forEach(l=>{l.uniforms.size>0&&l.uniforms.forEach((c,h)=>{h===r&&(c.value=a)})})};else if(o.name==="ShaderPass"){const r=o.fullscreenMaterial;for(const a in r.uniforms){if(a==="inputBuffer"||a==="map")continue;const l=r.uniforms[a],c=`${r.name.replace("Material","")} ${a}`;if(l.value===null&&t)s.push({title:c,prop:a,type:"image",value:{offset:[0,0],repeat:[1,1],src:""}});else if(l.value.isTexture&&t){const h=l.value,u=Ni.renderToBlob(h);s.push({title:c,prop:a,type:"image",value:{offset:[h.offset.x,h.offset.y],repeat:[h.repeat.x,h.repeat.y],src:u}})}else typeof l.value=="number"?s.push({title:c,prop:a,type:"number",value:l.value,step:.01}):typeof l.value=="string"?s.push({title:c,prop:a,type:"string",value:l.value}):typeof l.value=="boolean"&&s.push({title:c,prop:a,type:"boolean",value:l.value})}i=(a,l)=>{const c=r.uniforms[a];c.value=l}}else return;const n=`${o.name}: ${o.scene.name}`;e.addGroup({title:n,items:s,onUpdate:(r,a)=>{r==="Enabled"?o.enabled=a:i(r,a)}}),fh.push(n)}function px(o,e){o.passes.forEach(t=>{um(t,e)})}function fx(o){fh.forEach(e=>{o.removeGroup(e)}),fh=[]}function mx(o,e,t,s=1024){return new Promise(i=>{const n=e.aspect,r=e.fov,a=e.rotation.clone(),l=t.outputBuffer;e.aspect=1,e.fov=90,e.updateProjectionMatrix();const c=new y.WebGLRenderTarget(s,s,{format:y.RGBAFormat,depthBuffer:!0,stencilBuffer:!1});t.outputBuffer=c,Tn(o,c,e,"nx",t,s).then(()=>{Tn(o,c,e,"ny",t,s).then(()=>{Tn(o,c,e,"nz",t,s).then(()=>{Tn(o,c,e,"px",t,s).then(()=>{Tn(o,c,e,"py",t,s).then(()=>{Tn(o,c,e,"pz",t,s).then(()=>{e.aspect=n,e.fov=r,e.rotation.copy(a),e.updateMatrixWorld(),e.updateProjectionMatrix(),t.outputBuffer=l,c.dispose(),i()})})})})})})})}function Tn(o,e,t,s,i,n){return new Promise(r=>{const a=Math.PI/2;switch(s){case"nx":t.rotation.set(0,-a,0);break;case"ny":t.rotation.set(-a,0,Math.PI);break;case"nz":t.rotation.set(0,0,0);break;case"px":t.rotation.set(0,a,0);break;case"py":t.rotation.set(a,0,Math.PI);break;case"pz":t.rotation.set(0,Math.PI,0);break}t.updateMatrixWorld(),i.render();const l=new Uint8Array(n*n*4);o.readRenderTargetPixels(e,0,0,n,n,l);const c=document.createElement("canvas");c.width=c.height=n;const h=c.getContext("2d"),u=h.createImageData(n,n);u.data.set(l),h.putImageData(u,0,0);const d=document.createElement("canvas");d.width=d.height=n;const p=d.getContext("2d");p.translate(0,n),p.scale(1,-1),p.drawImage(c,0,0);const f=d.toDataURL("image/png"),m=document.createElement("a");m.href=f,m.download=`${t.name}_${s}.png`,document.body.appendChild(m),m.click(),m.remove(),r()})}const Sn=Zh(["ctrlKey","metaKey","shiftKey","button","pointerId","pointerType","clientX","clientY","pageX","pageY"]),gx=Zh(["clientX","clientY","deltaX","deltaY","deltaMode"]),yx=Zh(["ctrlKey","metaKey","shiftKey","keyCode"]);function xx(o,e){o.preventDefault(),gx(o,e)}function _x(o){o.preventDefault()}function bx(o,e,t){for(const s of e)t[s]=o[s]}function Zh(o){return function(t,s){const i={type:t.type};bx(t,o,i),s(i)}}function Gl(o,e){const t=[],s={type:o.type,touches:t};for(let i=0;i<o.touches.length;++i){const n=o.touches[i];t.push({pageX:n.pageX,pageY:n.pageY})}e(s)}const Tx={37:!0,38:!0,39:!0,40:!0};function Sx(o,e){const{keyCode:t}=o;Tx[t]&&(o.preventDefault(),yx(o,e))}const vx={contextmenu:_x,mousedown:Sn,mousemove:Sn,mouseup:Sn,pointerdown:Sn,pointermove:Sn,pointerup:Sn,touchstart:Gl,touchmove:Gl,touchend:Gl,wheel:xx,keydown:Sx};let wx=0;class Mx{id;worker;constructor(e,t,s){this.id=wx++,this.worker=t;const i=r=>{this.worker.postMessage({type:"event",id:this.id,data:r})};t.postMessage({type:"makeProxy",id:this.id});for(const[r,a]of Object.entries(s))e.addEventListener(r,l=>{a(l,i)});function n(){i({type:"resize",left:0,top:0,width:innerWidth,height:innerHeight})}window.addEventListener("resize",n),n()}}class dm extends y.EventDispatcher{style={};left=0;top=0;width=0;height=0;ownerDocument=void 0;constructor(){super(),this.ownerDocument=this}get clientWidth(){return this.width}set clientWidth(e){this.width=e}get clientHeight(){return this.height}set clientHeight(e){this.height=e}setPointerCapture(){}releasePointerCapture(){}getBoundingClientRect(){return{x:this.left,y:this.top,left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height,toJSON:()=>({})}}handleEvent(e){if(e.type==="size"){this.left=e.left,this.top=e.top,this.width=e.width,this.height=e.height;return}e.preventDefault=go,e.stopPropagation=go,this.dispatchEvent(e)}focus(){}getRootNode(){return this}}class Cx{targets={};constructor(){this.handleEvent=this.handleEvent.bind(this)}makeProxy(e){const{id:t}=e,s=new dm;this.targets[t]=s}getProxy(e){return this.targets[e]}handleEvent(e){this.targets[e.id]?.handleEvent(e.data)}}class Ex{assets={audio:new Map,image:new Map,json:new Map,model:new Map,video:new Map};components=new Map;settings={dpr:1,fps:30,width:0,height:0,mobile:!1,supportOffScreenCanvas:!1,supportWebGPU:!1,quality:"Low",dev:!1,editor:!1};onUpdateCallback;playing=!1;rafID=-1;dispose(){this.pause(),this.components.forEach(e=>e.dispose()),this.components.clear()}detectSettings(e=!1,t=!1){return new Promise(s=>{om(e,t).then(i=>{this.settings=i,s()})})}update(){}draw(){}play=()=>{this.playing||(this.playing=!0,this.onUpdate())};pause=()=>{this.playing&&(this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1)};onUpdate=()=>{this.update(),this.isApp&&this.draw(),this.onUpdateCallback&&this.onUpdateCallback(),this.rafID=requestAnimationFrame(this.onUpdate)};addComponent(e,t){this.components.set(e,t)}get debugEnabled(){return this.settings.dev}get isApp(){return!this.editor}set isApp(e){this.editor=!e}get editor(){return this.settings.editor}set editor(e){this.settings.editor=e}}class Kh{name;_debug=!1;_editor=!1;broadcastChannel;constructor(e,t=!1,s=!1){this.name=e,this._debug=t,this._editor=s,t&&(this.broadcastChannel=new BroadcastChannel(e),this.broadcastChannel.addEventListener("message",this.messageHandler.bind(this)))}dispose(){this.broadcastChannel?.removeEventListener("message",this.messageHandler.bind(this)),this.broadcastChannel?.close()}get debug(){return this._debug}get editor(){return this._editor}send(e){if(this.editor&&e.target==="app"||!this.editor&&e.target==="editor")try{this.broadcastChannel?.postMessage(e)}catch(s){console.log("Hermes - Error sending message:"),console.log(s),console.log(e)}}messageHandler(e){const t=e.data;t.target==="app"?this.handleApp(t):this.handleEditor(t)}handleApp(e){}handleEditor(e){}}function Ax(o,e,t,s,i){const n=1-o;return n*n*n*e+3*n*n*o*t+3*n*o*o*s+o*o*o*i}function Rx(o,e,t){if(o.type!=="bezier"||o.handles.length!==4)throw new Error("Invalid keyframe data for Bézier interpolation.");const[s,i]=o.handles,n=(t-o.position)/(e.position-o.position);return Ax(n,o.value,o.value+s,e.value+i,e.value)}class Nx extends Kh{project;sheets=new Map;sheetObjects=new Map;sheetObjectCBs=new Map;sheetObjectUnsubscribe=new Map;activeSheet;studio=void 0;rafDriver=void 0;constructor(e=!1,t=!1){super("RemoteTheatre",e,t)}dispose(){this.project=void 0,this.sheets=new Map,this.sheetObjects=new Map,this.sheetObjectCBs=new Map,this.sheetObjectUnsubscribe=new Map}loadProject(e,t,s){return this.project=oe.getProject(e,{state:s}),new Promise((i,n)=>{this.project?.ready.then(()=>{if(s){const r=s.sheetsById;for(const a in r)this.sheet(a)}t&&(this.rafDriver=oe.createRafDriver({name:e})),i()}).catch(()=>n())})}getSheetInstance(e,t){return t!==void 0?`${e}-${t}`:e}sheet(e,t){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const s=this.getSheetInstance(e,t);let i=this.sheets.get(s);return i!==void 0||(i=this.project?.sheet(e,t),this.sheets.set(s,i)),i}playSheet(e,t,s){return new Promise(i=>{const n=t!==void 0?{...t}:{};n.rafDriver=this.rafDriver,this.sheet(e,s)?.sequence.play(n).then(r=>i(r)),this.send({event:"playSheet",target:"editor",data:{sheet:e,instance:s,value:t}})})}pauseSheet(e,t){this.sheet(e,t)?.sequence.pause(),this.send({event:"pauseSheet",target:"editor",data:{sheet:e,instance:t}})}clearSheetObjects(e){this.sheetObjects.forEach((t,s)=>{s.search(`${e}_`)>-1&&this.unsubscribe(t)})}sheetObject(e,t,s,i,n){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const r=this.sheet(e,n);if(r===void 0)return;const l=`${this.getSheetInstance(e,n)}_${t}`;let c=this.sheetObjects.get(l),h=s;c!==void 0&&(h={...s,...c.value}),c=r.object(t,h,{reconfigure:!0}),this.sheetObjects.set(l,c),this.sheetObjectCBs.set(l,i!==void 0?i:go);function u(p,f,m){if(typeof m=="object")if(im(m))p[f]={r:m.r,g:m.g,b:m.b,a:m.a};else for(const x in m){const g=m[x];typeof g=="object"&&u(m,x,g)}}const d=c.onValuesChange(p=>{const f=this.sheetObjectCBs.get(l);if(this.editor){for(const m in p){const x=p[m];typeof x=="object"&&u(p,m,x)}this.send({event:"updateSheetObject",target:"app",data:{sheet:e,sheetObject:l,values:p}}),f&&f(p)}else f&&f(p)});return this.sheetObjectUnsubscribe.set(l,d),c}getSheetObjectKeyframes(e,t,s){const i=this.sheet(e);if(i===void 0)return[];const n=`${e}_${t}`,r=this.sheetObjects.get(n);return r===void 0?[]:i.sequence.__experimental_getKeyframes(r.props[s])}getSheetObjectVectors(e,t){const s=this.sheet(e);if(s===void 0)return[];const i=`${e}_${t}`,n=this.sheetObjects.get(i);if(n===void 0)return[];const r=[],a=s.sequence.__experimental_getKeyframes(n.props.x),l=s.sequence.__experimental_getKeyframes(n.props.y),c=s.sequence.__experimental_getKeyframes(n.props.z),h=new Set;return a.forEach(d=>h.add(d.position)),l.forEach(d=>h.add(d.position)),c.forEach(d=>h.add(d.position)),Array.from(h).sort((d,p)=>d-p).forEach(d=>{const p=(f,m)=>{const x=f.find((b,T)=>b.position<=m&&(f[T+1]?.position||1/0)>m),g=f.find(b=>b.position>m);if(!x)return g?.value||0;if(!g||x.position===m)return x.value;if(x.type==="bezier")return Rx(x,g,m);const _=(m-x.position)/(g.position-x.position);return x.value+_*(g.value-x.value)};r.push({position:d,x:p(a,d),y:p(l,d),z:p(c,d)})}),r}update(e){this.rafDriver?.tick(e)}unsubscribe(e){if(this.project===void 0){console.error("Theatre Project hasn't been created yet.");return}const t=e.address.sheetId,s=e.address.objectKey;this.sheets.get(t)?.detachObject(s);const n=`${t}_${s}`,r=this.sheetObjectUnsubscribe.get(n);r!==void 0&&(this.sheetObjects.delete(n),this.sheetObjectCBs.delete(n),this.sheetObjectUnsubscribe.delete(n),r())}handleApp(e){let t;switch(e.event){case"setSheet":t=this.sheets.get(e.data.sheet),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet: ${e.data.sheet}`,t);break;case"setSheetObject":t=this.sheetObjects.get(`${e.data.sheet}_${e.data.key}`),t!==void 0?this.studio?.setSelection([t]):console.log(`Hermes - Can't set Sheet Object: ${e.data.sheet}, ${e.data.key}: ${e.data.sheet}_${e.data.key}`,t);break;case"updateSheetObject":t=this.sheets.get(e.data.sheet),t!==void 0&&t.sequence.pause(),t=this.sheetObjectCBs.get(e.data.sheetObject),t!==void 0?t(e.data.values):console.log(`Hermes - Can't update Sheet Object: ${e.data.sheetObject}, ${e.data.sheet}`,t);break;case"updateTimeline":t=this.sheets.get(e.data.sheet),t!==void 0?t.sequence.position=e.data.position:console.log(`Hermes - Can't update sheet position: ${e.data.sheet}, ${e.data.position}`);break}}handleEditor(e){switch(e.event){case"playSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.play(e.data.value);break;case"pauseSheet":this.sheet(e.data.sheet,e.data.instance)?.sequence.pause();break}}getSheetNames(){const e=[];return this.sheets.forEach((t,s)=>{e.push(s)}),e}handleEditorApp(){if(this.editor){this.studio?.ui.restore(),this.studio?.onSelectionChange(i=>{i.length<1||i.forEach(n=>{let r=n.address.sheetId,a="setSheet",l={};switch(n.type){case"Theatre_Sheet_PublicAPI":a="setSheet",l={sheet:n.address.sheetId},this.activeSheet=this.sheets.get(n.address.sheetId);break;case"Theatre_SheetObject_PublicAPI":a="setSheetObject",r+=`_${n.address.objectKey}`,l={id:r,sheet:n.address.sheetId,key:n.address.objectKey},this.activeSheet=this.sheets.get(n.address.sheetId);break}this.send({event:a,target:"app",data:l})})});let e=-1;const t=()=>{if(this.activeSheet!==void 0&&e!==this.activeSheet.sequence.position){e=this.activeSheet.sequence.position;const i=this.activeSheet;this.send({event:"updateTimeline",target:"app",data:{position:e,sheet:i.address.sheetId}})}},s=()=>{t(),requestAnimationFrame(s)};t(),s()}else this.studio?.ui.hide()}}function Px(o){if(o.name==="cameras")return"camera";if(o.name==="interactive")return"interactive";if(o.name==="lights")return"light";if(o.name==="ui")return"ui";if(o.name==="utils")return"utils";const e=o.type;return e.search("Helper")>-1?"icon_utils":e.search("Camera")>-1?"camera":e.search("Light")>-1?"light":"obj3D"}function $n(o){const e={name:o.name,type:o.type,uuid:o.uuid,children:[]};return o.children.forEach(t=>{e.children.push($n(t))}),e}function Fx(o){const e={};for(const t in o){const s=o[t].value;e[t]={value:s},s===null?e[t].value={src:"",offset:[0,0],repeat:[1,1]}:s!==void 0&&s.isTexture&&(e[t].value={src:s.image.src,offset:[s.offset.x,s.offset.y],repeat:[s.repeat.x,s.repeat.y]})}return e}function Dx(o){switch(o){case"blendSrcAlpha":case"blendDstAlpha":case"blendEquationAlpha":case"clippingPlanes":case"shadowSide":case"precision":return!0}return!1}function vn(o){const e={};for(const t in o){if(t.substring(0,1)==="_"||t.substring(0,2)==="is"||Dx(t))continue;const s=typeof o[t],i=o[t];switch(s){case"boolean":case"number":case"string":e[t]=i;break;case"object":i!==null?(e[t]=i,i.isTexture?e[t]={src:Ni.renderToBlob(i),offset:[i.offset.x,i.offset.y],repeat:[i.repeat.x,i.repeat.y]}:t==="uniforms"&&(e[t]=Fx(e[t]))):t==="glslVersion"?e[t]="":e[t]={src:"",offset:[0,0],repeat:[1,1]};break}}return o.anisotropy!==void 0&&(e.anisotropy=o.anisotropy),o.clearcoat!==void 0&&(e.clearcoat=o.clearcoat),o.iridescence!==void 0&&(e.iridescence=o.iridescence),o.dispersion!==void 0&&(e.dispersion=o.dispersion),o.sheen!==void 0&&(e.sheen=o.sheen),o.transmission!==void 0&&(e.transmission=o.transmission),o.transmission!==void 0&&(e.transmission=o.transmission),e}function Vl(o){o.updateMatrix();const e={name:o.name,type:o.type,uuid:o.uuid,visible:o.visible,matrix:o.matrix.elements,animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};o.animations.forEach(s=>{e.animations.push({name:s.name,duration:s.duration,blendMode:s.blendMode})});const t=o.type.toLowerCase();if(t.search("mesh")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(vn(n))}),e.material=i}else e.material=vn(s.material)}else if(t.search("points")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(vn(n))}),e.material=i}else e.material=vn(s.material)}else if(t.search("line")>-1){const s=o;if(Array.isArray(s.material)){const i=[];s.material.forEach(n=>{i.push(vn(n))}),e.material=i}else e.material=vn(s.material)}else t.search("camera")>-1?o.type==="PerspectiveCamera"?e.perspectiveCameraInfo={fov:o.fov,zoom:o.zoom,near:o.near,far:o.far,focus:o.focus,aspect:o.aspect,filmGauge:o.filmGauge,filmOffset:o.filmOffset}:o.type==="OrthographicCamera"&&(e.orthographicCameraInfo={zoom:o.zoom,near:o.near,far:o.far,left:o.left,right:o.right,top:o.top,bottom:o.bottom}):t.search("light")>-1&&(e.lightInfo={color:o.color,intensity:o.intensity,decay:o.decay,distance:o.distance,angle:o.angle,penumbra:o.penumbra,groundColor:o.groundColor,width:o.width,height:o.height});return e}function Ox(o,e){const t=e.split(".");switch(t.length){case 1:return o[t[0]];case 2:return o[t[0]][t[1]];case 3:return o[t[0]][t[1]][t[2]];case 4:return o[t[0]][t[1]][t[2]][t[3]];case 5:return o[t[0]][t[1]][t[2]][t[3]][t[4]];case 6:return o[t[0]][t[1]][t[2]][t[3]][t[4]][t[5]]}}function Bx(o,e){for(const t in e)o[t]=e[t]}function Ye(o,e,t){if(o===void 0){console.log(`Hermes - Can't set props: ${e}`,t);return}const s=e.split("."),i=s.length;if(typeof t!="object")switch(i){case 1:o[s[0]]=t;break;case 2:o[s[0]][s[1]]=t;break;case 3:o[s[0]][s[1]][s[2]]=t;break;case 4:o[s[0]][s[1]][s[2]][s[3]]=t;break;case 5:o[s[0]][s[1]][s[2]][s[3]][s[4]]=t;break}else{let r;switch(i){case 1:r=o[s[0]];break;case 2:r=o[s[0]][s[1]];break;case 3:r=o[s[0]][s[1]][s[2]];break;case 4:r=o[s[0]][s[1]][s[2]][s[3]];break;case 5:r=o[s[0]][s[1]][s[2]][s[3]][s[4]];break}r!=null?Bx(r,t):console.log(`Hermes - Can't set props because target isn't found: ${e}`,t)}}function pm(o){return new Promise((e,t)=>{const s=new Image;s.onload=()=>{const i=new y.Texture(s);i.wrapS=y.RepeatWrapping,i.wrapT=y.RepeatWrapping,i.needsUpdate=!0,e(i)},s.onerror=t,s.src=o})}var ce=(o=>(o.CUSTOM="ToolEvents::custom",o.SELECT_DROPDOWN="ToolEvents::selectDropdown",o.DRAG_UPDATE="ToolEvents::dragUpdate",o.ADD_SCENE="ToolEvents::addScene",o.REFRESH_SCENE="ToolEvents::refreshScene",o.REMOVE_SCENE="ToolEvents::removeScene",o.SET_SCENE="ToolEvents::setScene",o.SET_OBJECT="ToolEvents::setObject",o.CLEAR_OBJECT="ToolEvents::clearObject",o.ADD_CAMERA="ToolEvents::addCamera",o.REMOVE_CAMERA="ToolEvents::removeCamera",o.ADD_GROUP="ToolEvents::addGroup",o.REMOVE_GROUP="ToolEvents::removeGroup",o.ADD_SPLINE="ToolEvents::addSpline",o.ADD_RENDERER="ToolEvents::addRenderer",o.UPDATE_RENDERER="ToolEvents::updateRenderer",o))(ce||{});class Ix extends Kh{name;canvas=null;inputElement=null;scene=void 0;scenes=new Map;renderer=void 0;renderTargets=new Map;renderTargetsResize=new Map;groups=new Map;_listeners={};constructor(e,t=!1,s=!1){super("RemoteThree",t,s),this.name=e}dispose(){this.scenes.forEach(e=>{Ls(e)}),this.scenes.clear(),this.scene&&Ls(this.scene),this.renderTargets.forEach(e=>{e.dispose()}),this.renderTargets.clear(),this.renderer?.dispose()}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){const i={...e,target:this},n=s.slice(0);for(let r=0,a=n.length;r<a;r++)n[r].call(this,i)}}getObjectByUUID(e){const t=e.split(".")[0],s=this.scenes.get(t);if(s!==void 0)return s.getObjectByProperty("uuid",e)}getObject(e){if(!this.debug)return;this.renderer!==void 0&&(Ni.renderer=this.renderer);const t=this.getObjectByUUID(e);t&&this.setObject(t)}setObject(e){this.renderer!==void 0&&(Ni.renderer=this.renderer);const t=Vl(e);this.dispatchEvent({type:"ToolEvents::setObject",value:t})}requestMethod(e,t,s,i){const n=this.getObjectByUUID(e);if(n)try{i!==void 0?Ox(n,i)[t](s):n[t](s)}catch(r){console.log("Hermes - Error requesting method:",e,t,s),console.log(r)}}updateObject(e,t,s){this.send({event:"updateObject",target:"app",data:{uuid:e,key:t,value:s}})}createTexture(e,t,s){this.send({event:"createTexture",target:"app",data:{uuid:e,key:t,value:s}})}onUpdateObject(e,t,s){const i=this.getObjectByUUID(e);i&&Ye(i,t,s)}onCreateTexture(e,t,s){const i=this.getObjectByUUID(e);if(i){const n=r=>{const a=t.split(".");switch(a.length){case 1:i[a[0]]=r;break;case 2:i[a[0]][a[1]]=r;break;case 3:i[a[0]][a[1]][a[2]]=r;break;case 4:i[a[0]][a[1]][a[2]][a[3]]=r;break;case 5:i[a[0]][a[1]][a[2]][a[3]][a[4]]=r;break}i.material.needsUpdate=!0};s.src.length>0?pm(s.src).then(r=>{r.offset.set(s.offset[0],s.offset[1]),r.repeat.set(s.repeat[0],s.repeat[1]),n(r)}):n(null)}}addGroup(e){this.groups.get(e.title)===void 0&&(this.groups.set(e.title,{title:e.title,onUpdate:e.onUpdate}),this.send({event:"addGroup",target:"editor",data:JSON.stringify(e)}))}removeGroup(e){this.groups.get(e)!==void 0&&(this.groups.delete(e),this.send({event:"removeGroup",target:"editor",data:e}))}updateGroup(e,t,s){this.send({event:"updateGroup",target:"app",data:JSON.stringify({group:e,prop:t,value:s})})}addSpline(e){setTimeout(()=>{this.send({event:"addSpline",target:"editor",data:JSON.stringify(e.toJSON())})},1)}setRenderer(e,t=null){if(this.renderer=e,this.canvas=e.domElement,this.inputElement=t!==null?t:this.canvas,!this.debug)return;const s=`#${e.getClearColor(new y.Color).getHexString()}`;this.send({event:"addRenderer",target:"editor",data:{autoClear:e.autoClear,autoClearColor:e.autoClearColor,autoClearDepth:e.autoClearDepth,autoClearStencil:e.autoClearStencil,outputColorSpace:e.outputColorSpace,localClippingEnabled:e.localClippingEnabled,clearColor:s,clearAlpha:e.getClearAlpha(),colorManagement:y.ColorManagement.enabled,toneMapping:e.toneMapping,toneMappingExposure:e.toneMappingExposure,type:e.isWebGLRenderer?"WebGLRenderer":"WebGPURenderer"}})}updateRenderer(e){this.send({event:"updateRenderer",target:"app",data:e})}addScene(e){if(e===void 0||(this.scenes.set(e.name,e),!this.debug))return;ph(),Ha(e);const t=$n(e);this.send({event:"addScene",target:"editor",data:t})}refreshScene(e){if(!this.debug)return;const t=this.scenes.get(e);if(t!==void 0){const s=$n(t);this.send({event:"refreshScene",target:"app",data:s})}}removeScene(e){if(e===void 0||(this.scenes.delete(e.name),!this.debug))return;const t=$n(e);this.send({event:"removeScene",target:"editor",data:t})}removeAllScenes(){this.scenes.forEach(e=>this.removeScene(e))}getScene(e){let t=null;return this.scene!==void 0&&this.scene.uuid.search(e)>-1?this.scene:(this.scenes.forEach((s,i)=>{e.search(i)>-1&&(t=s)}),t)}setScene(e){if(e===void 0||(this.scene=e,!this.debug))return;this.renderer!==void 0&&(Ni.renderer=this.renderer),ph(),Ha(e);const t=$n(e);this.send({event:"setScene",target:"editor",data:t})}requestSize(){this.send({event:"requestSize",target:"app"})}addCamera(e){if(!this.debug)return;const t=Vl(e);this.send({event:"addCamera",target:"editor",data:t})}removeCamera(e){if(!this.debug)return;const t=Vl(e);this.send({event:"removeCamera",target:"editor",data:t})}handleApp(e){switch(e.event){case"refreshScene":this.send({event:"refreshScene",target:"editor",data:$n(this.scenes.get(e.data.name))});break;case"updateRenderer":this.renderer&&(this.renderer.autoClearColor=e.data.autoClearColor,this.renderer.outputColorSpace=e.data.outputColorSpace,this.renderer.localClippingEnabled=e.data.localClippingEnabled,this.renderer.setClearColor(e.data.clearColor,e.data.clearAlpha),this.renderer.toneMapping=e.data.toneMapping,this.renderer.toneMappingExposure=e.data.toneMappingExposure,y.ColorManagement.enabled=e.data.colorManagement);break}if(e.event==="updateGroup"){const t=JSON.parse(e.data);this.groups.get(t.group)?.onUpdate(t.prop,t.value)}}handleEditor(e){switch(e.event){case"addScene":this.dispatchEvent({type:"ToolEvents::addScene",value:e.data});break;case"refreshScene":this.dispatchEvent({type:"ToolEvents::refreshScene",value:e.data});break;case"removeScene":this.dispatchEvent({type:"ToolEvents::removeScene",value:e.data});break;case"setScene":this.dispatchEvent({type:"ToolEvents::setScene",value:e.data});break;case"addCamera":this.dispatchEvent({type:"ToolEvents::addCamera",value:e.data});break;case"removeCamera":this.dispatchEvent({type:"ToolEvents::removeCamera",value:e.data});break;case"addGroup":this.dispatchEvent({type:"ToolEvents::addGroup",value:e.data});break;case"removeGroup":this.dispatchEvent({type:"ToolEvents::removeGroup",value:e.data});break;case"addSpline":this.dispatchEvent({type:"ToolEvents::addSpline",value:e.data});break;case"addRenderer":this.dispatchEvent({type:"ToolEvents::addRenderer",value:e.data})}}messageHandler(e){const t=e.data;if(t.event==="updateObject"){this.onUpdateObject(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="createTexture"){this.onCreateTexture(t.data.uuid,t.data.key,t.data.value);return}else if(t.event==="requestSize"){t.target==="app"?this.send({event:"requestSize",target:"editor",data:{width:this.width,height:this.height}}):this.scenes.forEach(s=>{s.resize!==void 0&&s.resize(t.data.width,t.data.height)});return}t.target==="app"?this.handleApp(t):this.handleEditor(t)}addRT(e,t=!0,s){const i=new y.WebGLRenderTarget(32,32,s);i.texture.name=e,this.renderTargets.set(e,i),this.renderTargetsResize.set(e,t)}removeRT(e){this.renderTargets.delete(e),this.renderTargetsResize.delete(e)}resize(e,t){const s=this.dpr;this.renderTargets.forEach((n,r)=>{this.renderTargetsResize.get(r)&&n.setSize(e*s,t*s)});const i=!(this.renderer?.domElement instanceof OffscreenCanvas);this.renderer?.setSize(e,t,i)}set dpr(e){this.renderer?.setPixelRatio(Si(1,2,e))}get dpr(){return this.renderer!==void 0?this.renderer?.getPixelRatio():1}get width(){return this.renderer!==void 0?this.renderer.domElement.width/this.dpr:0}get height(){return this.renderer!==void 0?this.renderer.domElement.height/this.dpr:0}}var Io={exports:{}},wr={};/**
|
|
19
19
|
* @license React
|
|
20
20
|
* react-jsx-runtime.production.min.js
|
|
21
21
|
*
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the MIT license found in the
|
|
25
25
|
* LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/var
|
|
26
|
+
*/var Sd;function Lx(){if(Sd)return wr;Sd=1;var o=W,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function r(a,l,c){var h,u={},d=null,p=null;c!==void 0&&(d=""+c),l.key!==void 0&&(d=""+l.key),l.ref!==void 0&&(p=l.ref);for(h in l)s.call(l,h)&&!n.hasOwnProperty(h)&&(u[h]=l[h]);if(a&&a.defaultProps)for(h in l=a.defaultProps,l)u[h]===void 0&&(u[h]=l[h]);return{$$typeof:e,type:a,key:d,ref:p,props:u,_owner:i.current}}return wr.Fragment=t,wr.jsx=r,wr.jsxs=r,wr}var Mr={};/**
|
|
27
27
|
* @license React
|
|
28
28
|
* react-jsx-runtime.development.js
|
|
29
29
|
*
|
|
@@ -31,23 +31,23 @@
|
|
|
31
31
|
*
|
|
32
32
|
* This source code is licensed under the MIT license found in the
|
|
33
33
|
* LICENSE file in the root directory of this source tree.
|
|
34
|
-
*/var
|
|
35
|
-
`+yn+v}}var
|
|
34
|
+
*/var vd;function Ux(){return vd||(vd=1,process.env.NODE_ENV!=="production"&&function(){var o=W,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),f=Symbol.iterator,m="@@iterator";function x(v){if(v===null||typeof v!="object")return null;var G=f&&v[f]||v[m];return typeof G=="function"?G:null}var g=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(v){{for(var G=arguments.length,Y=new Array(G>1?G-1:0),ee=1;ee<G;ee++)Y[ee-1]=arguments[ee];b("error",v,Y)}}function b(v,G,Y){{var ee=g.ReactDebugCurrentFrame,Ee=ee.getStackAddendum();Ee!==""&&(G+="%s",Y=Y.concat([Ee]));var De=Y.map(function(xe){return String(xe)});De.unshift("Warning: "+G),Function.prototype.apply.call(console[v],console,De)}}var T=!1,S=!1,C=!1,w=!1,R=!1,P;P=Symbol.for("react.module.reference");function z(v){return!!(typeof v=="string"||typeof v=="function"||v===s||v===n||R||v===i||v===c||v===h||w||v===p||T||S||C||typeof v=="object"&&v!==null&&(v.$$typeof===d||v.$$typeof===u||v.$$typeof===r||v.$$typeof===a||v.$$typeof===l||v.$$typeof===P||v.getModuleId!==void 0))}function $(v,G,Y){var ee=v.displayName;if(ee)return ee;var Ee=G.displayName||G.name||"";return Ee!==""?Y+"("+Ee+")":Y}function q(v){return v.displayName||"Context"}function j(v){if(v==null)return null;if(typeof v.tag=="number"&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof v=="function")return v.displayName||v.name||null;if(typeof v=="string")return v;switch(v){case s:return"Fragment";case t:return"Portal";case n:return"Profiler";case i:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof v=="object")switch(v.$$typeof){case a:var G=v;return q(G)+".Consumer";case r:var Y=v;return q(Y._context)+".Provider";case l:return $(v,v.render,"ForwardRef");case u:var ee=v.displayName||null;return ee!==null?ee:j(v.type)||"Memo";case d:{var Ee=v,De=Ee._payload,xe=Ee._init;try{return j(xe(De))}catch{return null}}}return null}var X=Object.assign,Z=0,we,de,ye,se,Me,ze,ot;function be(){}be.__reactDisabledLog=!0;function at(){{if(Z===0){we=console.log,de=console.info,ye=console.warn,se=console.error,Me=console.group,ze=console.groupCollapsed,ot=console.groupEnd;var v={configurable:!0,enumerable:!0,value:be,writable:!0};Object.defineProperties(console,{info:v,log:v,warn:v,error:v,group:v,groupCollapsed:v,groupEnd:v})}Z++}}function Ot(){{if(Z--,Z===0){var v={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:X({},v,{value:we}),info:X({},v,{value:de}),warn:X({},v,{value:ye}),error:X({},v,{value:se}),group:X({},v,{value:Me}),groupCollapsed:X({},v,{value:ze}),groupEnd:X({},v,{value:ot})})}Z<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Sr=g.ReactCurrentDispatcher,yn;function Po(v,G,Y){{if(yn===void 0)try{throw Error()}catch(Ee){var ee=Ee.stack.trim().match(/\n( *(at )?)/);yn=ee&&ee[1]||""}return`
|
|
35
|
+
`+yn+v}}var Dl=!1,Fo;{var t0=typeof WeakMap=="function"?WeakMap:Map;Fo=new t0}function sd(v,G){if(!v||Dl)return"";{var Y=Fo.get(v);if(Y!==void 0)return Y}var ee;Dl=!0;var Ee=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var De;De=Sr.current,Sr.current=null,at();try{if(G){var xe=function(){throw Error()};if(Object.defineProperty(xe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(xe,[])}catch(Bt){ee=Bt}Reflect.construct(v,[],xe)}else{try{xe.call()}catch(Bt){ee=Bt}v.call(xe.prototype)}}else{try{throw Error()}catch(Bt){ee=Bt}v()}}catch(Bt){if(Bt&&ee&&typeof Bt.stack=="string"){for(var me=Bt.stack.split(`
|
|
36
36
|
`),wt=ee.stack.split(`
|
|
37
|
-
`),qe=me.length-1,
|
|
38
|
-
`+me[qe].replace(" at new "," at ");return v.displayName&&Jt.includes("<anonymous>")&&(Jt=Jt.replace("<anonymous>",v.displayName)),typeof v=="function"&&
|
|
37
|
+
`),qe=me.length-1,Ke=wt.length-1;qe>=1&&Ke>=0&&me[qe]!==wt[Ke];)Ke--;for(;qe>=1&&Ke>=0;qe--,Ke--)if(me[qe]!==wt[Ke]){if(qe!==1||Ke!==1)do if(qe--,Ke--,Ke<0||me[qe]!==wt[Ke]){var Jt=`
|
|
38
|
+
`+me[qe].replace(" at new "," at ");return v.displayName&&Jt.includes("<anonymous>")&&(Jt=Jt.replace("<anonymous>",v.displayName)),typeof v=="function"&&Fo.set(v,Jt),Jt}while(qe>=1&&Ke>=0);break}}}finally{Dl=!1,Sr.current=De,Ot(),Error.prepareStackTrace=Ee}var _n=v?v.displayName||v.name:"",zi=_n?Po(_n):"";return typeof v=="function"&&Fo.set(v,zi),zi}function s0(v,G,Y){return sd(v,!1)}function i0(v){var G=v.prototype;return!!(G&&G.isReactComponent)}function Do(v,G,Y){if(v==null)return"";if(typeof v=="function")return sd(v,i0(v));if(typeof v=="string")return Po(v);switch(v){case c:return Po("Suspense");case h:return Po("SuspenseList")}if(typeof v=="object")switch(v.$$typeof){case l:return s0(v.render);case u:return Do(v.type,G,Y);case d:{var ee=v,Ee=ee._payload,De=ee._init;try{return Do(De(Ee),G,Y)}catch{}}}return""}var vr=Object.prototype.hasOwnProperty,id={},nd=g.ReactDebugCurrentFrame;function Oo(v){if(v){var G=v._owner,Y=Do(v.type,v._source,G?G.type:null);nd.setExtraStackFrame(Y)}else nd.setExtraStackFrame(null)}function n0(v,G,Y,ee,Ee){{var De=Function.call.bind(vr);for(var xe in v)if(De(v,xe)){var me=void 0;try{if(typeof v[xe]!="function"){var wt=Error((ee||"React class")+": "+Y+" type `"+xe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof v[xe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw wt.name="Invariant Violation",wt}me=v[xe](G,xe,ee,Y,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(qe){me=qe}me&&!(me instanceof Error)&&(Oo(Ee),_("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",ee||"React class",Y,xe,typeof me),Oo(null)),me instanceof Error&&!(me.message in id)&&(id[me.message]=!0,Oo(Ee),_("Failed %s type: %s",Y,me.message),Oo(null))}}}var r0=Array.isArray;function Ol(v){return r0(v)}function o0(v){{var G=typeof Symbol=="function"&&Symbol.toStringTag,Y=G&&v[Symbol.toStringTag]||v.constructor.name||"Object";return Y}}function a0(v){try{return rd(v),!1}catch{return!0}}function rd(v){return""+v}function od(v){if(a0(v))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",o0(v)),rd(v)}var ad=g.ReactCurrentOwner,l0={key:!0,ref:!0,__self:!0,__source:!0},ld,cd;function c0(v){if(vr.call(v,"ref")){var G=Object.getOwnPropertyDescriptor(v,"ref").get;if(G&&G.isReactWarning)return!1}return v.ref!==void 0}function h0(v){if(vr.call(v,"key")){var G=Object.getOwnPropertyDescriptor(v,"key").get;if(G&&G.isReactWarning)return!1}return v.key!==void 0}function u0(v,G){typeof v.ref=="string"&&ad.current}function d0(v,G){{var Y=function(){ld||(ld=!0,_("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};Y.isReactWarning=!0,Object.defineProperty(v,"key",{get:Y,configurable:!0})}}function p0(v,G){{var Y=function(){cd||(cd=!0,_("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};Y.isReactWarning=!0,Object.defineProperty(v,"ref",{get:Y,configurable:!0})}}var f0=function(v,G,Y,ee,Ee,De,xe){var me={$$typeof:e,type:v,key:G,ref:Y,props:xe,_owner:De};return me._store={},Object.defineProperty(me._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(me,"_self",{configurable:!1,enumerable:!1,writable:!1,value:ee}),Object.defineProperty(me,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Ee}),Object.freeze&&(Object.freeze(me.props),Object.freeze(me)),me};function m0(v,G,Y,ee,Ee){{var De,xe={},me=null,wt=null;Y!==void 0&&(od(Y),me=""+Y),h0(G)&&(od(G.key),me=""+G.key),c0(G)&&(wt=G.ref,u0(G,Ee));for(De in G)vr.call(G,De)&&!l0.hasOwnProperty(De)&&(xe[De]=G[De]);if(v&&v.defaultProps){var qe=v.defaultProps;for(De in qe)xe[De]===void 0&&(xe[De]=qe[De])}if(me||wt){var Ke=typeof v=="function"?v.displayName||v.name||"Unknown":v;me&&d0(xe,Ke),wt&&p0(xe,Ke)}return f0(v,me,wt,Ee,ee,ad.current,xe)}}var Bl=g.ReactCurrentOwner,hd=g.ReactDebugCurrentFrame;function xn(v){if(v){var G=v._owner,Y=Do(v.type,v._source,G?G.type:null);hd.setExtraStackFrame(Y)}else hd.setExtraStackFrame(null)}var Il;Il=!1;function Ll(v){return typeof v=="object"&&v!==null&&v.$$typeof===e}function ud(){{if(Bl.current){var v=j(Bl.current.type);if(v)return`
|
|
39
39
|
|
|
40
|
-
Check the render method of \``+v+"`."}return""}}function
|
|
40
|
+
Check the render method of \``+v+"`."}return""}}function g0(v){return""}var dd={};function y0(v){{var G=ud();if(!G){var Y=typeof v=="string"?v:v.displayName||v.name;Y&&(G=`
|
|
41
41
|
|
|
42
|
-
Check the top-level render call using <`+Y+">.")}return
|
|
42
|
+
Check the top-level render call using <`+Y+">.")}return G}}function pd(v,G){{if(!v._store||v._store.validated||v.key!=null)return;v._store.validated=!0;var Y=y0(G);if(dd[Y])return;dd[Y]=!0;var ee="";v&&v._owner&&v._owner!==Bl.current&&(ee=" It was passed a child from "+j(v._owner.type)+"."),xn(v),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',Y,ee),xn(null)}}function fd(v,G){{if(typeof v!="object")return;if(Ol(v))for(var Y=0;Y<v.length;Y++){var ee=v[Y];Ll(ee)&&pd(ee,G)}else if(Ll(v))v._store&&(v._store.validated=!0);else if(v){var Ee=x(v);if(typeof Ee=="function"&&Ee!==v.entries)for(var De=Ee.call(v),xe;!(xe=De.next()).done;)Ll(xe.value)&&pd(xe.value,G)}}}function x0(v){{var G=v.type;if(G==null||typeof G=="string")return;var Y;if(typeof G=="function")Y=G.propTypes;else if(typeof G=="object"&&(G.$$typeof===l||G.$$typeof===u))Y=G.propTypes;else return;if(Y){var ee=j(G);n0(Y,v.props,"prop",ee,v)}else if(G.PropTypes!==void 0&&!Il){Il=!0;var Ee=j(G);_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Ee||"Unknown")}typeof G.getDefaultProps=="function"&&!G.getDefaultProps.isReactClassApproved&&_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function _0(v){{for(var G=Object.keys(v.props),Y=0;Y<G.length;Y++){var ee=G[Y];if(ee!=="children"&&ee!=="key"){xn(v),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",ee),xn(null);break}}v.ref!==null&&(xn(v),_("Invalid attribute `ref` supplied to `React.Fragment`."),xn(null))}}var md={};function gd(v,G,Y,ee,Ee,De){{var xe=z(v);if(!xe){var me="";(v===void 0||typeof v=="object"&&v!==null&&Object.keys(v).length===0)&&(me+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var wt=g0();wt?me+=wt:me+=ud();var qe;v===null?qe="null":Ol(v)?qe="array":v!==void 0&&v.$$typeof===e?(qe="<"+(j(v.type)||"Unknown")+" />",me=" Did you accidentally export a JSX literal instead of a component?"):qe=typeof v,_("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",qe,me)}var Ke=m0(v,G,Y,Ee,De);if(Ke==null)return Ke;if(xe){var Jt=G.children;if(Jt!==void 0)if(ee)if(Ol(Jt)){for(var _n=0;_n<Jt.length;_n++)fd(Jt[_n],v);Object.freeze&&Object.freeze(Jt)}else _("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else fd(Jt,v)}if(vr.call(G,"key")){var zi=j(v),Bt=Object.keys(G).filter(function(M0){return M0!=="key"}),Ul=Bt.length>0?"{key: someKey, "+Bt.join(": ..., ")+": ...}":"{key: someKey}";if(!md[zi+Ul]){var w0=Bt.length>0?"{"+Bt.join(": ..., ")+": ...}":"{}";_(`A props object containing a "key" prop is being spread into JSX:
|
|
43
43
|
let props = %s;
|
|
44
44
|
<%s {...props} />
|
|
45
45
|
React keys must be passed directly to JSX without using spread:
|
|
46
46
|
let props = %s;
|
|
47
|
-
<%s key={someKey} {...props} />`,
|
|
47
|
+
<%s key={someKey} {...props} />`,Ul,zi,w0,zi),md[zi+Ul]=!0}}return v===s?_0(Ke):x0(Ke),Ke}}function b0(v,G,Y){return gd(v,G,Y,!0)}function T0(v,G,Y){return gd(v,G,Y,!1)}var S0=T0,v0=b0;Mr.Fragment=s,Mr.jsx=S0,Mr.jsxs=v0}()),Mr}var wd;function kx(){return wd||(wd=1,process.env.NODE_ENV==="production"?Io.exports=Lx():Io.exports=Ux()),Io.exports}var E=kx();function Qh(o){return o.title.search("<")>-1?E.jsx("button",{className:"svg",dangerouslySetInnerHTML:{__html:o.title}}):E.jsx("button",{children:o.title})}const zx=E.jsxs("svg",{className:"closeIcon",width:"14",height:"14",fill:"none",stroke:"#666666",strokeMiterlimit:"10",children:[E.jsx("circle",{cx:"7",cy:"7",r:"6"}),E.jsx("line",{x1:"4",y1:"4",x2:"10",y2:"10"}),E.jsx("line",{x1:"4",y1:"10",x2:"10",y2:"4"})]}),Gx=E.jsx("svg",{className:"dragIcon",width:"14",height:"14",fill:"#666666",stroke:"none",children:E.jsx("path",{d:`M10.43,4H3.57C3.26,4,3,4.22,3,4.5v1C3,5.78,3.26,6,3.57,6h6.86C10.74,6,11,5.78,11,5.5v-1\r
|
|
48
48
|
C11,4.22,10.74,4,10.43,4z M10.43,8H3.57C3.26,8,3,8.22,3,8.5v1C3,9.78,3.26,10,3.57,10h6.86C10.74,10,11,9.78,11,9.5v-1\r
|
|
49
|
-
C11,8.22,10.74,8,10.43,8z`})});function hm(o){return E.jsx("li",{className:`reorder-item ${o.draggingIndex===o.index?"dragging":""}`,draggable:!0,onDragStart:()=>o.onDragStart(o.index),onDragOver:e=>{e.preventDefault(),o.onDragOver(o.index)},onDragEnd:o.onDragEnd,children:E.jsxs("div",{children:[yx,E.jsx("span",{children:o.title}),E.jsx("button",{className:"closeIcon",onClick:()=>o.onDelete(o.index),children:gx})]})})}function um(o){const[e,t]=W.useState(!1),[s,i]=W.useState(o.options),[n,r]=W.useState(null),a=p=>{o.onDragComplete(p),i(p)},l=p=>{const f=[...s];f.splice(p,1),a(f)},c=p=>{r(p)},h=p=>{if(n===p||n===null)return;const f=[...s],m=f.splice(n,1)[0];f.splice(p,0,m),r(p),i(f)},u=()=>{o.onDragComplete(s),r(null)};let d="dropdown draggable";return o.subdropdown&&(d+=" subdropdown"),E.jsxs("div",{className:d,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[E.jsx(Zh,{title:o.title}),E.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((p,f)=>E.jsx(hm,{title:p,index:f,draggingIndex:n,onDelete:l,onDragStart:c,onDragOver:h,onDragEnd:u},p))})]})}function dm(o){const[e,t]=W.useState(!1),s=[];o.options.map((n,r)=>{o.onSelect!==void 0&&(n.onSelect=o.onSelect),s.push(E.jsx(pm,{option:n},r))});let i="dropdown";return o.subdropdown&&(i+=" subdropdown"),E.jsxs("div",{className:i,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[E.jsx(Zh,{title:o.title}),E.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function pm(o){const{option:e}=o,[t,s]=W.useState("");let i;switch(e.type){case"draggable":i=E.jsx(um,{title:e.title,options:e.value,onDragComplete:n=>{e.onDragComplete!==void 0&&e.onDragComplete(n)},subdropdown:!0});break;case"dropdown":i=E.jsx(dm,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":i=E.jsx("button",{onClick:()=>{e.onSelect!==void 0&&e.onSelect(e.value),e.selectable&&(t!==e.title?s(e.title):s(""))},children:e.title});break}return E.jsx("li",{className:t===e.title?"selected":"",children:i},ht())}function go(o){const[e,t]=W.useState(o.open!==void 0?o.open:!0),s=!e||o.children===void 0,i=W.useRef(null),n=()=>{o.three.dispatchEvent({type:de.REMOVE_SCENE,value:o.scene})};return E.jsxs("div",{className:`accordion ${s?"hide":""}`,children:[E.jsxs("button",{className:"toggle",onClick:()=>{const r=!e;o.onToggle!==void 0&&o.onToggle(r),t(r)},children:[E.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),E.jsx("p",{className:"label",children:mo(o.label)})]}),o.onRefresh?E.jsxs(E.Fragment,{children:[E.jsx("button",{className:"visibility",ref:i,onClick:()=>{const a=o.three.getScene(o.scene.uuid);if(a){const l=!a.visible;a.visible=l,i.current.style.opacity=l?"1":"0.25"}}}),E.jsx("button",{className:"refresh",onClick:o.onRefresh}),E.jsx("button",{className:"remove",onClick:n})]}):null,o.button,E.jsx("div",{className:e?"open":"",children:E.jsx("div",{children:o.children})},Math.random())]})}function Qh(o){if(o.child===void 0)return console.log("Hermes - No child attached"),null;const e=W.useRef(null),[t,s]=W.useState(!1),i=o.child.children.length>0,n=[];return o.child.children.length>0&&o.child.children.map((r,a)=>{n.push(E.jsx(Qh,{child:r,three:o.three},a))}),W.useEffect(()=>{if(o.child){const r=o.child.uuid.split(".")[0],a=o.three.getScene(r);if(a!==null)try{const l=a.getObjectByProperty("uuid",o.child.uuid);l!==void 0?e.current.style.opacity=l.visible?"1":"0.25":console.log(`Hermes - Can't find child: ${o.child.uuid}`)}catch(l){console.log("Error looking for child:",l),console.log(o.child),console.log(o.three.scenes),console.log(a)}else console.log(`Hermes (ChildObject) - Can't find Scene: ${r} with child UUID: ${o.child.uuid}`,o.three.scenes,o.three.scene,a)}},[t]),E.jsxs("div",{className:"childObject",children:[E.jsxs("div",{className:"child",children:[i?E.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,E.jsx("button",{className:"name",style:{left:i?"20px":"5px"},onClick:()=>{o.child!==void 0?(o.three.getObject(o.child.uuid),!t&&i&&s(!0)):console.log("Hermes - No child attached...")},children:o.child.name.length>0?`${o.child.name} (${o.child.type})`:`${o.child.type}::${o.child.uuid}`}),E.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(o.child){const r=o.three.getScene(o.child.uuid);if(r!==null){const a=r.getObjectByProperty("uuid",o.child.uuid);if(a!==void 0){const l="visible",c=!a.visible;e.current.style.opacity=c?"1":"0.25",o.three.updateObject(o.child.uuid,l,c),Ye(a,l,c)}else console.log(`Hermes - Couldn't find object: ${o.child.uuid}`,r)}else console.log(`Hermes - Couldn't find object in scene: ${o.child.uuid}, ${o.child.name}`)}}}),E.jsx("div",{className:`icon ${ax(o.child)}`})]}),E.jsx("div",{className:t?"open":"",children:E.jsx("div",{className:"container",children:n})})]},Math.random())}function dh(o){const e=[];return o.child?.children.map((t,s)=>{e.push(E.jsx(Qh,{child:t,scene:o.scene,three:o.three},s))}),E.jsx("div",{className:`scene ${o.class!==void 0?o.class:""}`,children:e})}function Zr(o){const[e,t]=W.useState(o.defaultValue);return W.useEffect(()=>{let s=!1,i=-1,n=0,r=o.defaultValue,a=!1;const l=p=>{a=p.ctrlKey},c=p=>{s=!0,n=Number(o.input.current?.value),i=p.clientX,document.addEventListener("mouseup",u,!1),document.addEventListener("mousemove",h,!1),document.addEventListener("contextmenu",u,!1)},h=p=>{if(!s)return;const f=o.step!==void 0?o.step:1,m=(p.clientX-i)*f*(a?10:1);r=Number((n+m).toFixed(4)),o.min!==void 0&&(r=Math.max(r,o.min)),o.max!==void 0&&(r=Math.min(r,o.max)),o.onChange!==void 0&&o.onChange(r),t(r)},u=()=>{s=!1,document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u)},d=p=>{const f=Number(p.target.value);o.onChange!==void 0&&o.onChange(f),t(f)};return o.label.current?.addEventListener("mousedown",c,!1),o.sliderRef!==void 0&&o.sliderRef.current?.addEventListener("input",d),document.addEventListener("keydown",l,!1),document.addEventListener("keyup",l,!1),()=>{o.label.current?.removeEventListener("mousedown",c),o.sliderRef!==void 0&&o.sliderRef.current?.removeEventListener("input",d),document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u),document.removeEventListener("keydown",l),document.addEventListener("keyup",l,!1)}},[]),e}function hn(o){const e=W.useRef(null),t=W.useRef(null),[s,i]=W.useState(o.value);return Zr({label:o.labelRef,input:e,sliderRef:t,defaultValue:s,min:o.min,max:o.max,step:o.step,onChange:n=>{i(n),o.onChange!==void 0&&o.onChange(o.prop,n)}}),E.jsxs(E.Fragment,{children:[o.type==="number"&&E.jsx("input",{alt:o.alt,className:o.className,ref:e,type:"number",value:s,min:o.min,max:o.max,step:o.step,disabled:o.disabled,name:ht(),onChange:n=>{if(i(n.target.value),n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||o.onChange!==void 0&&o.onChange(o.prop,r)}}),o.type==="range"&&E.jsxs(E.Fragment,{children:[E.jsx("input",{type:"text",value:s.toString(),disabled:o.disabled,ref:e,className:"min",name:ht(),onChange:n=>{if(n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||(i(r),o.onChange!==void 0&&o.onChange(o.prop,r))}}),E.jsx("input",{disabled:o.disabled,type:"range",value:s,min:o.min,max:o.max,step:o.step,ref:t,name:ht(),onChange:fo})]})]})}function xx(o){const e=W.useRef(null),t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),a=W.useRef(null),l=W.useRef(null),c=W.useRef(null),h=W.useRef(null),[u,d]=W.useState(o.value.x),[p,f]=W.useState(o.value.y),[m,y]=W.useState({min:Math.min(o.min,Math.min(o.value.x,o.value.y)),max:Math.max(o.max,Math.max(o.value.x,o.value.y))}),[g,_]=W.useState(!1);Zr({label:a,input:e,defaultValue:u,min:m.min,max:m.max,step:.01,onChange:P=>{d(P),o.onChange({target:{value:{x:P,y:p}}})}}),Zr({label:l,input:t,defaultValue:p,min:m.min,max:m.max,step:.01,onChange:P=>{f(P),o.onChange({target:{value:{x:u,y:P}}})}}),Zr({label:c,input:s,defaultValue:m.min,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{y({min:P,max:m.max})}}),Zr({label:h,input:i,defaultValue:m.max,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{y({min:m.min,max:P})}});function b(){g||(window.addEventListener("mousemove",S),window.addEventListener("mouseup",T),_(!0))}function T(){window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",T),_(!1)}function S(P){const z=n.current.getBoundingClientRect(),$=Si(0,99,P.clientX-z.left)/99,q=1-Si(0,99,P.clientY-z.top)/99,j=is(or(m.min,m.max,$),3),X=is(or(m.min,m.max,q),3);o.onChange({target:{value:{x:j,y:X}}}),d(j),f(X)}function C(){const P=Number(s.current.value);y({min:P,max:m.max}),u<P&&d(Si(P,m.max,u)),p<P&&f(Si(P,m.max,p))}function w(){const P=Number(i.current.value);y({min:m.min,max:P}),u>P&&d(Si(m.min,P,u)),p>P&&f(Si(m.min,P,p))}W.useEffect(()=>{r.current.style.left=`${za(m.min,m.max,u)*100}%`,r.current.style.top=`${(1-za(m.min,m.max,p))*100}%`},[m,u,p]);const R=o.step!==void 0?o.step:.01;return E.jsxs("div",{className:"vector2",children:[E.jsxs("div",{className:"fields",children:[E.jsxs("div",{children:[E.jsx("span",{ref:a,children:"X"}),E.jsx("input",{ref:e,type:"number",value:u,min:m.min,max:m.max,step:R,name:ht(),onChange:P=>{if(d(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(o.onChange({target:{value:{x:z,y:p}}}),z<m.min&&y({min:z,max:m.max}))}})]}),E.jsxs("div",{children:[E.jsx("span",{ref:l,children:"Y"}),E.jsx("input",{ref:t,type:"number",value:p,min:m.min,max:m.max,step:R,name:ht(),onChange:P=>{if(f(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(o.onChange({target:{value:{x:u,y:z}}}),z>m.max&&y({min:m.min,max:z}))}})]}),E.jsxs("div",{children:[E.jsx("span",{ref:c,children:"Min"}),E.jsx("input",{ref:s,type:"number",value:m.min,step:R,name:ht(),onChange:C})]}),E.jsxs("div",{children:[E.jsx("span",{ref:h,children:"Max"}),E.jsx("input",{ref:i,type:"number",value:m.max,step:R,name:ht(),onChange:w})]})]}),E.jsxs("div",{className:"input",ref:n,onMouseDown:b,onMouseUp:T,children:[E.jsx("div",{className:"x"}),E.jsx("div",{className:"y"}),E.jsx("div",{className:"pt",ref:r})]})]})}const yt=["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"];let Sd=1234567;const ro=Math.PI/180,ar=180/Math.PI;function Qs(){const o=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return(yt[o&255]+yt[o>>8&255]+yt[o>>16&255]+yt[o>>24&255]+"-"+yt[e&255]+yt[e>>8&255]+"-"+yt[e>>16&15|64]+yt[e>>24&255]+"-"+yt[t&63|128]+yt[t>>8&255]+"-"+yt[t>>16&255]+yt[t>>24&255]+yt[s&255]+yt[s>>8&255]+yt[s>>16&255]+yt[s>>24&255]).toLowerCase()}function pe(o,e,t){return Math.max(e,Math.min(t,o))}function Kh(o,e){return(o%e+e)%e}function Ji(o,e,t,s,i){return s+(o-e)*(i-s)/(t-e)}function _x(o,e,t){return o!==e?(t-o)/(e-o):0}function Pi(o,e,t){return(1-t)*o+t*e}function bx(o,e,t,s){return Pi(o,e,1-Math.exp(-t*s))}function Tx(o,e=1){return e-Math.abs(Kh(o,e*2)-e)}function Sx(o,e,t){return o<=e?0:o>=t?1:(o=(o-e)/(t-e),o*o*(3-2*o))}function vx(o,e,t){return o<=e?0:o>=t?1:(o=(o-e)/(t-e),o*o*o*(o*(o*6-15)+10))}function wx(o,e){return o+Math.floor(Math.random()*(e-o+1))}function Mx(o,e){return o+Math.random()*(e-o)}function Cx(o){return o*(.5-Math.random())}function Ex(o){o!==void 0&&(Sd=o);let e=Sd+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Ga(o){return o*ro}function fm(o){return o*ar}function Ax(o){return(o&o-1)===0&&o!==0}function Rx(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function Nx(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function Px(o,e,t,s,i){const n=Math.cos,r=Math.sin,a=n(t/2),l=r(t/2),c=n((e+s)/2),h=r((e+s)/2),u=n((e-s)/2),d=r((e-s)/2),p=n((s-e)/2),f=r((s-e)/2);switch(i){case"XYX":o.set(a*h,l*u,l*d,a*c);break;case"YZY":o.set(l*d,a*h,l*u,a*c);break;case"ZXZ":o.set(l*u,l*d,a*h,a*c);break;case"XZX":o.set(a*h,l*f,l*p,a*c);break;case"YXY":o.set(l*p,a*h,l*f,a*c);break;case"ZYZ":o.set(l*f,l*p,a*h,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Rt(o,e){switch(e.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("Invalid component type.")}}function ae(o,e){switch(e.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("Invalid component type.")}}const Fx={DEG2RAD:ro,RAD2DEG:ar,generateUUID:Qs,clamp:pe,euclideanModulo:Kh,mapLinear:Ji,inverseLerp:_x,lerp:Pi,damp:bx,pingpong:Tx,smoothstep:Sx,smootherstep:vx,randInt:wx,randFloat:Mx,randFloatSpread:Cx,seededRandom:Ex,degToRad:Ga,radToDeg:fm,isPowerOfTwo:Ax,ceilPowerOfTwo:Rx,floorPowerOfTwo:Nx,setQuaternionFromProperEuler:Px,normalize:ae,denormalize:Rt};function vd(o){const e=o.value.x!==void 0&&o.value.y!==void 0&&o.value.z!==void 0,t=o.value.isEuler!==void 0,s=o.value.elements!==void 0,i=o.step!==void 0?o.step:.01,n=[];if(t){const r=W.useMemo(()=>o.value,[]);["_x","_y","_z"].forEach(l=>{const c=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("span",{ref:c,children:l.substring(1).toUpperCase()}),E.jsx(hn,{value:fm(r[l]),type:"number",prop:l,step:.1,labelRef:c,onChange:(h,u)=>{r[h]=Ga(u),o.onChange({target:{value:r}})}})]},l))})}else if(e){const r=W.useMemo(()=>o.value,[]),a=(c,h)=>{r[c]=h,o.onChange({target:{value:r}})};["x","y","z"].forEach(c=>{const h=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("label",{ref:h,children:c.toUpperCase()}),E.jsx(hn,{value:r[c],type:"number",prop:c,step:i,labelRef:h,onChange:a})]},c))})}else if(s){const r=W.useMemo(()=>o.value,[]),a=(l,c)=>{const h=Number(l);r.elements[h]=c,o.onChange({target:{value:r}})};for(let l=0;l<9;l++){const c=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("label",{ref:c,children:l+1}),E.jsx(hn,{value:r.elements[l],type:"number",prop:l.toString(),step:i,labelRef:c,onChange:a})]},l.toString()))}}return E.jsx("div",{className:"grid3",children:n},Math.random().toString())}function Dx(o){const e=o.value.x!==void 0,t=o.step!==void 0?o.step:.01,s=[];if(e){const i=W.useMemo(()=>o.value,[]),n=(a,l)=>{i[a]=l,o.onChange({target:{value:i}})};["x","y","z","w"].forEach(a=>{const l=W.useRef(null);s.push(E.jsxs("div",{children:[E.jsx("label",{ref:l,children:a.toUpperCase()}),E.jsx(hn,{value:i[a],type:"number",prop:a,step:t,labelRef:l,onChange:n})]},a))})}else{const i=W.useMemo(()=>o.value,[]),n=(r,a)=>{const l=Number(r);i.elements[l]=a,o.onChange({target:{value:i}})};for(let r=0;r<16;r++){const a=W.useRef(null);s.push(E.jsxs("div",{children:[E.jsx("span",{ref:a,children:r+1}),E.jsx(hn,{value:i.elements[r],type:"number",prop:r.toString(),step:t,labelRef:a,onChange:n})]},r.toString()))}}return E.jsx("div",{className:"grid4",children:s})}function Ox(o){return!(o==="defaultAttributeValues"||o==="forceSinglePass"||o==="linecap"||o==="linejoin"||o==="linewidth"||o==="normalMapType"||o==="precision"||o==="shadowSide"||o==="uniformsGroups"||o==="uniformsNeedUpdate"||o==="userData"||o==="version"||o==="wireframeLinecap"||o==="wireframeLinejoin"||o==="wireframeLinewidth"||o.slice(0,4)==="clip"||o.slice(0,7)==="polygon"||o.slice(0,7)==="stencil"||o.slice(0,2)==="is")}function Bx(o){switch(o){case"Alpha Map":return"alphaMap";case"Anisotropy Map":return"anisotropyMap";case"AO Map":return"aoMap";case"Bump Map":return"bumpMap";case"Clearcoat Map":return"clearcoatMap";case"Clearcoat Normal Map":return"clearcoatNormalMap";case"Clearcoat Roughness Map":return"clearcoatRoughnessMap";case"Displacement Map":return"displacementMap";case"Emissive Map":return"emissiveMap";case"Gradient Map":return"gradientMap";case"Iridescence Map":return"iridescenceMap";case"Iridescence Thickness Map":return"iridescenceThicknessMap";case"Map":return"map";case"Matcap":return"matcap";case"Normal Map":return"normalMap";case"Roughness Map":return"roughnessMap";case"Sheen Color Map":return"sheenColorMap";case"Sheen Roughness Map":return"sheenRoughnessMap";case"Specular Color Map":return"specularColorMap";case"Specular Map Intensity":return"specularIntensityMap";case"Thickness Map":return"thicknessMap";case"Transmission Map":return"transmissionMap"}return o}function cl(o){switch(o){case"alphaHash":return"Alpha Hash";case"alphaMap":return"Alpha Map";case"alphaToCoverage":return"Alpha To Coverage";case"anisotropy":return"Anisotropy";case"anisotropyMap":return"Anisotropy Map";case"anisotropyRotation":return"Anisotropy Rotation";case"aoMap":return"AO Map";case"aoMapIntensity":return"AO Map Intensity";case"attenuationColor":return"Attenuation Color";case"attenuationDistance":return"Attenuation Distance";case"blendAlpha":return"Blend Alpha";case"blendColor":return"Blend Color";case"blendDst":return"Blend Dst";case"blendDstAlpha":return"Blend Dst Alha";case"blendEquation":return"Blend Equation";case"blendEquationAlpha":return"Blend Equation Alpha";case"blending":return"Blending";case"blendSrc":return"Blend Src";case"blendSrcAlpha":return"Blend Src Alpha";case"bumpMap":return"Bump Map";case"bumpScale":return"Bump Scale";case"clearcoat":return"Clearcoat";case"clearcoatMap":return"Clearcoat Map";case"clearcoatNormalMap":return"Clearcoat Normal Map";case"clearcoatNormalScale":return"Clearcoat Normal Scale";case"clearcoatRoughness":return"Clearcoat Roughness";case"clearcoatRoughnessMap":return"Clearcoat Roughness Map";case"color":return"Color";case"colorWrite":return"Color Write";case"defines":return"Defines";case"depthFunc":return"Depth Func";case"depthTest":return"Depth Test";case"depthWrite":return"Depth Write";case"dispersion":return"Dispersion";case"displacementBias":return"Displacement Bias";case"displacementMap":return"Displacement Map";case"displacementScale":return"Displacement Scale";case"dithering":return"Dithering";case"emissive":return"Emissive";case"emissiveMap":return"Emissive Map";case"emissiveIntensity":return"Emissive Intensity";case"envMap":return"Environment Map";case"envMapIntensity":return"Environment Map Intensity";case"envMapRotation":return"Environment Map Rotation";case"extensions":return"Extensions";case"flatShading":return"Flat Shading";case"fragmentShader":return"Fragment Shader";case"fog":return"Fog";case"glslVersion":return"GLSL Version";case"gradientMap":return"Gradient Map";case"ior":return"IOR";case"iridescence":return"Iridescence";case"iridescenceIOR":return"Iridescence IOR";case"iridescenceMap":return"Iridescence Map";case"iridescenceThicknessMap":return"Iridescence Thickness Map";case"iridescenceThicknessRange":return"Iridescence Thickness Range";case"lights":return"Lights";case"lightMap":return"Light Map";case"lightMapIntensity":return"Light Map Intensity";case"map":return"Map";case"matcap":return"Matcap";case"metalness":return"Metalness";case"metalnessMap":return"Metalness Map";case"name":return"Name";case"normalMap":return"Normal Map";case"normalScale":return"Normal Scale";case"premultipliedAlpha":return"Premultiplied Alpha";case"opacity":return"Opacity";case"reflectivity":return"Reflectivity";case"refractionRatio":return"Refraction Ratio";case"roughness":return"Roughness";case"roughnessMap":return"Roughness Map";case"sheen":return"Sheen";case"sheenColor":return"Sheen Color";case"sheenColorMap":return"Sheen Color Map";case"sheenRoughness":return"Sheen Roughness";case"sheenRoughnessMap":return"Sheen Roughness Map";case"shininess":return"Shininess";case"side":return"Side";case"size":return"Size";case"sizeAttenuation":return"Size Attenuation";case"specular":return"Specular";case"specularColor":return"Specular Color";case"specularColorMap":return"Specular Color Map";case"specularIntensity":return"Specular Intensity";case"specularIntensityMap":return"Specular Map Intensity";case"thickness":return"Thickness";case"thicknessMap":return"Thickness Map";case"toneMapped":return"Tone Mapped";case"transmission":return"Transmission";case"transmissionMap":return"Transmission Map";case"transparent":return"Transparent";case"type":return"Type";case"uuid":return"UUID";case"uniforms":return"Uniforms";case"vertexColors":return"Vertex Colors";case"vertexShader":return"Vertex Shader";case"visible":return"Visible";case"wireframe":return"Wireframe"}return o}function mm(o){const e=o.toLowerCase();return e.search("intensity")>-1||e==="anisotropyrotation"||e==="blendalpha"||e==="bumpscale"||e==="clearcoatroughness"||e==="displacementbias"||e==="displacementscale"||e==="metalness"||e==="opacity"||e==="reflectivity"||e==="refractionratio"||e==="roughness"||e==="sheenroughness"}function Ix(){const o=document.createElement("input");return o.type="file",new Promise((e,t)=>{o.addEventListener("change",function(){if(o.files===null)t();else{const s=o.files[0],i=new FileReader;i.onload=function(n){e(n.target.result)},i.readAsDataURL(s)}}),o.click()})}const Lx=[{title:"Front",value:x.FrontSide},{title:"Back",value:x.BackSide},{title:"Double",value:x.DoubleSide}],Ux=[{title:"No Blending",value:x.NoBlending},{title:"Normal",value:x.NormalBlending},{title:"Additive",value:x.AdditiveBlending},{title:"Subtractive",value:x.SubtractiveBlending},{title:"Multiply",value:x.MultiplyBlending},{title:"Custom",value:x.CustomBlending}],kx=[{title:"Add",value:x.AddEquation},{title:"Subtract",value:x.SubtractEquation},{title:"Reverse Subtract",value:x.ReverseSubtractEquation},{title:"Min",value:x.MinEquation},{title:"Max",value:x.MaxEquation}],zx=[{title:"Zero",value:x.ZeroFactor},{title:"One",value:x.OneFactor},{title:"Src Color",value:x.SrcColorFactor},{title:"One Minus Src Color",value:x.OneMinusSrcColorFactor},{title:"Src Alpha",value:x.SrcAlphaFactor},{title:"One Minus Src Alpha",value:x.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:x.DstAlphaFactor},{title:"One Minus Dst Alpha",value:x.OneMinusDstAlphaFactor},{title:"Dst Color",value:x.DstColorFactor},{title:"One Minus Dst Color",value:x.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:x.SrcAlphaSaturateFactor},{title:"Constant Color",value:x.ConstantColorFactor},{title:"One Minus Constant Color",value:x.OneMinusConstantColorFactor},{title:"Constant Alpha",value:x.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:x.OneMinusConstantAlphaFactor}],Vx=[{title:"Zero",value:x.ZeroFactor},{title:"One",value:x.OneFactor},{title:"Src Color",value:x.SrcColorFactor},{title:"One Minus Src Color",value:x.OneMinusSrcColorFactor},{title:"Src Alpha",value:x.SrcAlphaFactor},{title:"One Minus Src Alpha",value:x.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:x.DstAlphaFactor},{title:"One Minus Dst Alpha",value:x.OneMinusDstAlphaFactor},{title:"Dst Color",value:x.DstColorFactor},{title:"One Minus Dst Color",value:x.OneMinusDstColorFactor},{title:"Constant Color",value:x.ConstantColorFactor},{title:"One Minus Constant Color",value:x.OneMinusConstantColorFactor},{title:"Constant Alpha",value:x.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:x.OneMinusConstantAlphaFactor}];function wr(o,e){o.needsUpdate=!0,o.type="option",o.options=e}function Gx(o,e,t,s){return{type:"boolean",title:cl(o),prop:o,value:e,needsUpdate:!0,onChange:(i,n)=>{s.updateObject(t.uuid,`material.${o}`,n),s.updateObject(t.uuid,"material.needsUpdate",!0);const r=s.getScene(t.uuid);if(r!==null){const a=r.getObjectByProperty("uuid",t.uuid);Ye(a,`material.${o}`,n)}}}}function Hx(o,e,t,s){const i={type:"number",title:cl(o),prop:o,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(n,r)=>{s.updateObject(t.uuid,`material.${o}`,r),s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",t.uuid);Ye(l,`material.${o}`,r)}}};switch(o){case"blending":wr(i,Ux);break;case"blendDst":wr(i,Vx);break;case"blendEquation":wr(i,kx);break;case"blendSrc":wr(i,zx);break;case"side":wr(i,Lx);break}return mm(o)&&(i.value=Number(e),i.type="range",i.min=Math.min(0,i.value),i.max=Math.max(1,i.value),i.step=.01),i}function Wx(o,e,t,s){const i={type:"string",title:cl(o),prop:o,value:e,needsUpdate:!0,onChange:(r,a)=>{s.updateObject(t.uuid,`material.${o}`,a),s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);Ye(c,`material.${o}`,a)}},onKeyDown:r=>{}};return(o==="vertexShader"||o==="fragmentShader")&&(i.type="field",i.disabled=!1,i.latest=i.value,i.onChange=(r,a)=>{i.latest=a,s.updateObject(t.uuid,`material.${o}`,a);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);Ye(c,`material.${o}`,a)}},i.onKeyDown=r=>{if(r.key==="Enter"&&(r.altKey||r.metaKey)){s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",t.uuid);Ye(l,"material.needsUpdate",!0)}}}),i}function $x(o){return o.x!==void 0&&o.y!==void 0&&o.z===void 0}function jx(o){return o.x!==void 0&&o.y!==void 0&&o.z!==void 0&&o.w===void 0}function qx(o){return o.x!==void 0&&o.y!==void 0&&o.z!==void 0&&o.w!==void 0}function ph(o){o.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function Qr(o,e,t,s,i="",n=!1){const r=cl(o).split(".")[0].replaceAll("[","").replaceAll("]",""),a=i.length>0?`${i}.${o}`:o,l=typeof e;if(l==="boolean"||l==="string")return{title:r,prop:a,type:l,value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(l==="number"){const c={title:r,prop:a,type:"number",value:e,step:.01,disabled:n,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${a}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);Ye(p,`material.${a}`,u)}}};return mm(r)&&(c.type="range",c.min=0,c.max=1),c}else{if(e.isColor)return{title:r,prop:a,type:"color",value:e,disabled:n,onChange:(c,h)=>{const u=new x.Color(h);s.updateObject(t.uuid,`material.${a}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);Ye(p,`material.${a}`,u)}}};if(Array.isArray(e)){const c=[];for(const h in e){const u=e[h],d=`[${h.toString()}]`;if(u.value!==void 0){const p=Qr(`${d}.value`,u.value,t,s,a,n);p!==void 0&&c.push(p)}else{const p=Qr(d,u,t,s,a,n);p!==void 0&&c.push(p)}}if(c.length>0)return ph(c),{title:r,items:c}}else{if($x(e))return{title:r,prop:a,type:"vector2",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(jx(e))return{title:r,prop:a,type:"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(qx(e))return{title:r,prop:a,type:"grid4",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(e.isEuler)return{title:r,prop:a,type:"euler",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(e.src!==void 0)return{title:r,type:"image",value:e,disabled:n,onChange:(c,h)=>{const u=Bx(o),d=i.length>0?`${i}.${u}`:u;s.createTexture(t.uuid,`material.${d}`,h);const p=s.getScene(t.uuid);if(p!==null){const f=p.getObjectByProperty("uuid",t.uuid);if(f!==void 0){const m=y=>{const g=f.material,_=d.split(".");switch(_.length){case 1:g[_[0]]=y;break;case 2:g[_[0]][_[1]]=y;break;case 3:g[_[0]][_[1]][_[2]]=y;break;case 4:g[_[0]][_[1]][_[2]][_[3]]=y;break;case 5:g[_[0]][_[1]][_[2]][_[3]][_[4]]=y;break}g.needsUpdate=!0};h.src.length>0?cm(h.src).then(y=>{y.offset.set(h.offset[0],h.offset[1]),y.repeat.set(h.repeat[0],h.repeat[1]),m(y)}):m(null)}}}};if(e.elements!==void 0)return{title:r,prop:a,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};{const c=[],h=o==="defines"||o==="extensions";try{for(const u in e){const d=e[u];if(d!==void 0)if(d.value!==void 0){const p=Qr(`${u}.value`,d.value,t,s,a,h);p!==void 0&&c.push(p)}else{const p=Qr(u,d,t,s,a,h);p!==void 0&&c.push(p)}}}catch{console.log("Hermes - Issue cycling through material object:",o,e)}if(c.length>0)return ph(c),{title:r,items:c}}}}}function wd(o,e,t){const s=[];for(const i in o){if(!Ox(i))continue;const n=typeof o[i],r=o[i];if(n==="boolean")s.push(Gx(i,r,e,t));else if(n==="number")s.push(Hx(i,r,e,t));else if(n==="string")s.push(Wx(i,r,e,t));else if(n==="object"){const a=Qr(i,r,e,t);a!==void 0&&s.push(a)}else r!==void 0&&console.log("Hermes - Other Material Prop Type:",i,n,r)}return ph(s),s.push({title:"Update Material",type:"button",onChange:()=>{t.updateObject(e.uuid,"material.needsUpdate",!0);const i=t.getScene(e.uuid);if(i!==null){const n=i.getObjectByProperty("uuid",e.uuid);Ye(n,"material.needsUpdate",!0)}}}),s}function Yx(o,e){function t(){return`${e.name}_material`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=o.material;if(Array.isArray(r)){const a=[],l=r.length;for(let c=0;c<l;c++)a.push(E.jsx(hs,{three:e,title:`Material ${c}`,items:wd(r[c],o,e)},`Material ${c}`));return E.jsx(E.Fragment,{children:a})}else return E.jsx(hs,{three:e,title:"Material",items:wd(r,o,e),expanded:i,onToggle:a=>{n(a)}})}const Md="data:image/gif;base64,R0lGODlhDgFkAIAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDIgNzkuZGJhM2RhM2I1LCAyMDIzLzEyLzE1LTEwOjQyOjM3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjUuNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyMDk3M0NEODAxQjQxMUVGODVGNENDMkUyMUExNDk1NSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMDk3M0NEOTAxQjQxMUVGODVGNENDMkUyMUExNDk1NSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkE4ODc3Qzg5MDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4ODc3QzhBMDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAAA4BZAAAAv+Mj6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqTkJAGDQ+dnpuekmGgAKejpKuiZqmprKqoZKGyrbOlqrejub6xvLGyw8TFzcprurGuvqybxq7ETbrItsCz0l7Zpc+6p9/cS967w9/S2FTF0u/mzehK4Oqz3eTl9vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxo0XHDt6/AgypMiRJEuaPIkypcqVLFt+KwAAOw==";function Xx(o){const e=o.step!==void 0?o.step:.01,t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),[a]=W.useState(o.value),[l,c]=W.useState(o.value.offset[0]),[h,u]=W.useState(o.value.offset[1]),[d,p]=W.useState(o.value.repeat[0]),[f,m]=W.useState(o.value.repeat[1]);function y(_,b,T,S,C){if(o.onChange!==void 0){const w=o.prop!==void 0?o.prop:o.title;o.onChange(w,{src:_,offset:[b,T],repeat:[S,C]})}}function g(_){const b=t.current.src,T=_.target.value;switch(_.target){case s.current:c(T),y(b,T,h,d,f);break;case i.current:u(T),y(b,l,T,d,f);break;case n.current:p(T),y(b,l,h,T,f);break;case r.current:m(T),y(b,l,h,d,T);break}}return E.jsxs("div",{className:"imageField",children:[E.jsx("img",{alt:o.title,ref:t,onClick:()=>{Ix().then(_=>{t.current.src=_,y(_,l,h,d,f)})},src:a.src.length>0?a.src:Md}),E.jsxs("div",{className:"fields",children:[E.jsxs("div",{children:[E.jsx("span",{children:"Offset:"}),E.jsx("input",{ref:s,type:"number",value:l,step:e,name:ht(),onChange:g}),E.jsx("input",{ref:i,type:"number",value:h,step:e,name:ht(),onChange:g})]}),E.jsxs("div",{children:[E.jsx("span",{children:"Repeat:"}),E.jsx("input",{ref:n,type:"number",value:d,step:e,name:ht(),onChange:g}),E.jsx("input",{ref:r,type:"number",value:f,step:e,name:ht(),onChange:g})]}),E.jsx("button",{onClick:()=>{y("",l,h,d,f),t.current.src=Md},children:"Clear"})]})]})}function Ea(o){let e=o.value;e!==void 0&&(e.isColor!==void 0?e=lh(o.value):o.type==="color"&&(e=lh(new x.Color().setStyle(o.value,x.LinearSRGBColorSpace))));const[t,s]=W.useState(e),i=W.useRef(null),n=c=>{let h=c.target.value;if(o.type==="boolean")h=c.target.checked;else if(o.type==="option"&&(typeof o.value=="number"?h=Number(h):typeof o.value=="boolean"?h=!!h:typeof o.value=="object"&&(h=JSON.parse(h)),o.options!==void 0)){const u=o.options.length;for(let d=0;d<u&&o.options[d].value!==h;d++);}s(h),o.onChange!==void 0&&o.onChange(o.prop!==void 0?o.prop:o.title,h)},r={};o.disabled&&(r.opacity=.8);const a=o.type==="field"||o.type==="string"&&(t.length>100||t.search(`
|
|
50
|
-
`)>-1),l=a||o.type==="image"||o.type==="vector2";return E.jsxs("div",{className:`field ${l?"block":""}`,style:r,children:[o.type!=="button"&&E.jsx("span",{ref:i,children:mo(o.title)},"fieldLabel"),o.type==="string"&&!a&&E.jsx("input",{type:"text",disabled:o.disabled,onChange:n,value:t,name:ht()}),(o.type==="field"||o.type==="string"&&a)&&E.jsx("textarea",{cols:50,rows:10,disabled:o.disabled!==void 0?o.disabled:!0,onChange:n,onKeyDown:c=>{o.onKeyDown!==void 0&&o.onKeyDown(c)},value:t,name:ht()}),o.type==="boolean"&&E.jsx("input",{type:"checkbox",disabled:o.disabled,onChange:n,checked:t,name:ht()}),o.type==="number"&&E.jsx(hn,{value:t,type:o.type,prop:o.prop!==void 0?o.prop:o.title,min:o.min,max:o.max,step:o.step,disabled:o.disabled,labelRef:i,onChange:o.onChange}),o.type==="range"&&E.jsx(hn,{value:t,type:o.type,prop:o.prop!==void 0?o.prop:o.title,min:o.min,max:o.max,step:o.step,disabled:o.disabled,labelRef:i,onChange:o.onChange}),o.type==="color"&&E.jsxs(E.Fragment,{children:[E.jsx("input",{type:"text",value:t.toString(),onChange:n,disabled:o.disabled,className:"color",name:ht()}),E.jsx("input",{type:"color",value:t,onChange:n,disabled:o.disabled,name:ht()})]}),o.type==="button"&&E.jsx("button",{disabled:o.disabled,onClick:()=>{o.onChange!==void 0&&o.onChange(o.prop!==void 0?o.prop:o.title,!0)},children:o.title}),o.type==="image"&&E.jsx(Xx,{title:o.title,prop:o.prop,value:o.value,onChange:o.onChange}),o.type==="option"&&E.jsx(E.Fragment,{children:E.jsx("select",{onChange:n,disabled:o.disabled,defaultValue:o.value,name:ht(),children:o.options?.map((c,h)=>E.jsx("option",{value:c.value,children:mo(c.title)},h))})}),o.type==="vector2"&&E.jsx(xx,{step:o.step,value:t,min:0,max:1,onChange:n}),o.type==="grid3"&&E.jsx(vd,{step:o.step,value:t,onChange:n}),o.type==="grid4"&&E.jsx(Dx,{step:o.step,value:t,onChange:n}),o.type==="euler"&&E.jsx(vd,{step:o.step,value:t,onChange:n})]})}function Zx(o){return"items"in o}class hs extends W.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;three;constructor(e){super(e),this.three=e.three,this.state={lastUpdated:Date.now()}}addGroup(e){const t=[];e.items.forEach(n=>{t.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(r,a)=>{e.onUpdate(r,a)}})});const s=W.createRef(),i=E.jsx(hs,{three:this.props.three,ref:s,title:e.title,expanded:e.expanded,items:t},Math.random());return this.subgroupNames.push(e.title),this.subgroupElements.push(i),this.setState({lastUpdated:Date.now()}),s}removeGroup(e){const t=this.subgroupNames.length;for(let s=0;s<t;s++){const i=this.subgroupNames[s];if(e===i){this.subgroupNames.splice(s,1),this.subgroupElements.splice(s,1),this.setState({lastUpdated:Date.now()});return}}}setField(e,t){this.valueOverrides.set(e,t),this.setState({lastUpdated:Date.now()})}render(){const e=[];return this.props.items.forEach(t=>{if(Zx(t))e.push(E.jsx(hs,{three:this.props.three,title:mo(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),i=s!==void 0?s:t.value;e.push(E.jsx(Ea,{title:t.title,prop:t.prop,value:i,type:t.type,min:t.min,max:t.max,step:t.step,disabled:t.disabled,options:t.options,onChange:(n,r)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(n,r))},onKeyDown:n=>{t.onKeyDown!==void 0&&t.onKeyDown(n)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),E.jsx(go,{three:this.props.three,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class Ne extends W.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static three;constructor(e){super(e),this.state={lastUpdate:Date.now()},Ne.instance=this,Ne.three=e.three,e.three.addEventListener(de.ADD_GROUP,this.addGroup),e.three.addEventListener(de.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){this.props.three.removeEventListener(de.ADD_GROUP,this.addGroup),this.props.three.removeEventListener(de.REMOVE_GROUP,this.removeGroup)}render(){return E.jsx("div",{className:"customGroups",children:Ne.groups},this.state.lastUpdate)}addGroup=e=>{const t=JSON.parse(e.value),s=[];t.items.forEach(i=>{s.push({type:i.type,prop:i.prop,title:i.title!==void 0?i.title:i.prop,value:i.value,min:i.min,max:i.max,step:i.step,options:i.options,disabled:i.disabled,onChange:(n,r)=>{this.props.three.updateGroup(t.title,n,r)}})}),Ne.groups.push(E.jsx(hs,{three:this.props.three,title:t.title,items:s},Math.random())),Ne.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=Ne.groupTitles.length;for(let i=0;i<s;i++)if(t===Ne.groupTitles[i]){Ne.groups.splice(i,1),Ne.groupTitles.splice(i,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(e){const t=[];e.items.forEach(n=>{t.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(r,a)=>{e.onUpdate(r,a)}})});const s=W.createRef(),i=E.jsx(hs,{three:Ne.three,ref:s,title:e.title,items:t},Math.random());return Ne.groups.push(i),Ne.groupsRefs.push(s),Ne.groupTitles.push(e.title),s}static removeEditorGroup(e){const t=Ne.groupTitles.length;for(let s=0;s<t;s++)if(e===Ne.groupTitles[s]){Ne.groups.splice(s,1),Ne.groupTitles.splice(s,1),Ne.instance.setState({lastUpdate:Date.now()});return}}static removeAllGroups(){for(let e=Ne.groupTitles.length;e>0;e--)Ne.groups.splice(e,1),Ne.groupTitles.splice(e,1);Ne.instance.setState({lastUpdate:Date.now()})}}function Cd(o){switch(o){case"fov":return"FOV";case"zoom":return"Zoom";case"near":return"Near";case"far":return"Far";case"focus":return"Focus";case"aspect":return"Aspect";case"filmGauge":return"Film Gauge";case"filmOffset":return"Film Offset";case"left":return"Left";case"right":return"Right";case"top":return"Top";case"bottom":return"Bottom"}return o}function Qx(o,e){function t(){return`${e.name}_camera`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=[];if(o.perspectiveCameraInfo!==void 0)for(const a in o.perspectiveCameraInfo)r.push({title:Cd(a),prop:a,type:"number",step:.01,value:o.perspectiveCameraInfo[a],onChange:(l,c)=>{e.updateObject(o.uuid,l,c),e.requestMethod(o.uuid,"updateProjectionMatrix");const h=e.getScene(o.uuid);if(h!==null){const u=h.getObjectByProperty("uuid",o.uuid);u!==void 0&&(Ye(u,l,c),u.updateProjectionMatrix())}}});else if(o.orthographicCameraInfo!==void 0)for(const a in o.orthographicCameraInfo)r.push({title:Cd(a),prop:a,type:"number",step:.01,value:o.orthographicCameraInfo[a],onChange:(l,c)=>{e.updateObject(o.uuid,l,c),e.requestMethod(o.uuid,"updateProjectionMatrix");const h=e.getScene(o.uuid);if(h!==null){const u=h.getObjectByProperty("uuid",o.uuid);u!==void 0&&(Ye(u,l,c),u.updateProjectionMatrix())}}});return E.jsx(hs,{three:e,title:"Camera",items:r,expanded:i,onToggle:a=>{n(a)}})}class Kx{constructor(e,t){this.nodes=e,this.info=t,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this._animationLoop!==null&&this._animationLoop(t,s)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class vs{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let s=this.weakMap;for(let i=0;i<e.length-1;i++){const n=e[i];s.has(n)===!1&&s.set(n,new WeakMap),s=s.get(n)}return s.set(e[e.length-1],t),this}delete(e){let t=this.weakMap;for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return!1;return t.delete(e[e.length-1])}}const gm="177",Jx=0,e_=1,t_=2,s_=0,i_=1,Aa=3,Ks=0,Vt=1,Qn=2,lr=0,Js=1,Ha=2,Wa=3,$a=4,oo=5,bs=100,ym=101,xm=102,n_=103,r_=104,vi=200,_m=201,bm=202,Tm=203,ja=204,qa=205,Sm=206,vm=207,wm=208,Mm=209,Cm=210,Em=0,Am=1,Rm=2,Ya=3,Nm=4,Pm=5,Fm=6,Dm=7,hl=0,o_=1,a_=2,Kn=0,l_=1,c_=2,h_=3,u_=4,d_=6,p_=7,Jh=300,yo=301,Xa=302,eu=303,tu=304,fh=306,cr=1e3,Ri=1001,hr=1002,ut=1003,Om=1004,xo=1005,Kt=1006,mh=1007,ei=1008,Nt=1009,ao=1010,lo=1011,$n=1012,Et=1013,Xe=1014,Qt=1015,rs=1016,f_=1017,m_=1018,Fi=1020,Bm=35902,g_=1021,su=1022,os=1023,Bs=1026,ti=1027,iu=1028,nu=1029,cn=1030,ru=1031,y_=1032,ou=1033,zl=33776,Ra=33777,Na=33778,Pa=33779,Ed=35840,Ad=35841,Rd=35842,Nd=35843,Pd=36196,gh=37492,yh=37496,xh=37808,_h=37809,bh=37810,Th=37811,Sh=37812,vh=37813,wh=37814,Mh=37815,Ch=37816,Eh=37817,Ah=37818,Rh=37819,Nh=37820,Ph=37821,Vl=36492,x_=36283,Fd=36284,Dd=36285,Od=36286,Di=0,__=1,ri="",Xt="srgb",Jn="srgb-linear",Za="linear",te="srgb",b_=0,en=7680,T_=7681,S_=7682,v_=7683,w_=34055,M_=34056,C_=5386,E_=512,A_=513,R_=514,N_=515,P_=516,F_=517,D_=518,Fh=519,Im=512,au=513,Lm=514,Um=515,km=516,zm=517,Vm=518,Gm=519,Qa=35044,jn=35048,Ut=2e3,Oi=2001;class Ht{constructor(e,t,s,i,n,r,a,l,c){Ht.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,i,n,r,a,l,c)}set(e,t,s,i,n,r,a,l,c){const h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=n,h[5]=l,h[6]=s,h[7]=r,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const 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){const s=e.elements,i=t.elements,n=this.elements,r=s[0],a=s[3],l=s[6],c=s[1],h=s[4],u=s[7],d=s[2],p=s[5],f=s[8],m=i[0],y=i[3],g=i[6],_=i[1],b=i[4],T=i[7],S=i[2],C=i[5],w=i[8];return n[0]=r*m+a*_+l*S,n[3]=r*y+a*b+l*C,n[6]=r*g+a*T+l*w,n[1]=c*m+h*_+u*S,n[4]=c*y+h*b+u*C,n[7]=c*g+h*T+u*w,n[2]=d*m+p*_+f*S,n[5]=d*y+p*b+f*C,n[8]=d*g+p*T+f*w,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8];return t*r*h-t*a*c-s*n*h+s*a*l+i*n*c-i*r*l}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=h*r-a*c,d=a*l-h*n,p=c*n-r*l,f=t*u+s*d+i*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return e[0]=u*m,e[1]=(i*c-h*s)*m,e[2]=(a*s-i*r)*m,e[3]=d*m,e[4]=(h*t-i*l)*m,e[5]=(i*n-a*t)*m,e[6]=p*m,e[7]=(s*l-c*t)*m,e[8]=(r*t-s*n)*m,this}transpose(){let e;const 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){const 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,s,i,n,r,a){const l=Math.cos(n),c=Math.sin(n);return this.set(s*l,s*c,-s*(l*r+c*a)+r+e,-i*c,i*l,-i*(-c*r+l*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Gl.makeScale(e,t)),this}rotate(e){return this.premultiply(Gl.makeRotation(-e)),this}translate(e,t){return this.premultiply(Gl.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){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<9;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Gl=new Ht;function Hm(o){for(let e=o.length-1;e>=0;--e)if(o[e]>=65535)return!0;return!1}function Dh(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function O_(){const o=Dh("canvas");return o.style.display="block",o}const Bd={};function oi(o){o in Bd||(Bd[o]=!0,console.warn(o))}const Id=new Ht().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Ld=new Ht().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function B_(){const o={enabled:!0,workingColorSpace:Jn,spaces:{},convert:function(i,n,r){return this.enabled===!1||n===r||!n||!r||(this.spaces[n].transfer===te&&(i.r=si(i.r),i.g=si(i.g),i.b=si(i.b)),this.spaces[n].primaries!==this.spaces[r].primaries&&(i.applyMatrix3(this.spaces[n].toXYZ),i.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===te&&(i.r=er(i.r),i.g=er(i.g),i.b=er(i.b))),i},workingToColorSpace:function(i,n){return this.convert(i,this.workingColorSpace,n)},colorSpaceToWorking:function(i,n){return this.convert(i,n,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ri?Za:this.spaces[i].transfer},getLuminanceCoefficients:function(i,n=this.workingColorSpace){return i.fromArray(this.spaces[n].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,n,r){return i.copy(this.spaces[n].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,n){return oi("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(i,n)},toWorkingColorSpace:function(i,n){return oi("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(i,n)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],s=[.3127,.329];return o.define({[Jn]:{primaries:e,whitePoint:s,transfer:Za,toXYZ:Id,fromXYZ:Ld,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Xt},outputColorSpaceConfig:{drawingBufferColorSpace:Xt}},[Xt]:{primaries:e,whitePoint:s,transfer:te,toXYZ:Id,fromXYZ:Ld,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Xt}}}),o}const Ue=B_();function si(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function er(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}const Wm={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},di={h:0,s:0,l:0},Io={h:0,s:0,l:0};function Hl(o,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?o+(e-o)*6*t:t<1/2?e:t<2/3?o+(e-o)*6*(2/3-t):o}class ve{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(t===void 0&&s===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Xt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ue.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Ue.workingColorSpace){return this.r=e,this.g=t,this.b=s,Ue.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Ue.workingColorSpace){if(e=Kh(e,1),t=pe(t,0,1),s=pe(s,0,1),t===0)this.r=this.g=this.b=s;else{const n=s<=.5?s*(1+t):s+t-s*t,r=2*s-n;this.r=Hl(r,n,e+1/3),this.g=Hl(r,n,e),this.b=Hl(r,n,e-1/3)}return Ue.colorSpaceToWorking(this,i),this}setStyle(e,t=Xt){function s(n){n!==void 0&&parseFloat(n)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let n;const r=i[1],a=i[2];switch(r){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setRGB(Math.min(255,parseInt(n[1],10))/255,Math.min(255,parseInt(n[2],10))/255,Math.min(255,parseInt(n[3],10))/255,t);if(n=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setRGB(Math.min(100,parseInt(n[1],10))/100,Math.min(100,parseInt(n[2],10))/100,Math.min(100,parseInt(n[3],10))/100,t);break;case"hsl":case"hsla":if(n=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setHSL(parseFloat(n[1])/360,parseFloat(n[2])/100,parseFloat(n[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(r===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Xt){const s=Wm[e.toLowerCase()];return s!==void 0?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),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=si(e.r),this.g=si(e.g),this.b=si(e.b),this}copyLinearToSRGB(e){return this.r=er(e.r),this.g=er(e.g),this.b=er(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return Ue.workingToColorSpace(xt.copy(this),e),Math.round(pe(xt.r*255,0,255))*65536+Math.round(pe(xt.g*255,0,255))*256+Math.round(pe(xt.b*255,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ue.workingColorSpace){Ue.workingToColorSpace(xt.copy(this),t);const s=xt.r,i=xt.g,n=xt.b,r=Math.max(s,i,n),a=Math.min(s,i,n);let l,c;const h=(a+r)/2;if(a===r)l=0,c=0;else{const u=r-a;switch(c=h<=.5?u/(r+a):u/(2-r-a),r){case s:l=(i-n)/u+(i<n?6:0);break;case i:l=(n-s)/u+2;break;case n:l=(s-i)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Ue.workingColorSpace){return Ue.workingToColorSpace(xt.copy(this),t),e.r=xt.r,e.g=xt.g,e.b=xt.b,e}getStyle(e=Xt){Ue.workingToColorSpace(xt.copy(this),e);const t=xt.r,s=xt.g,i=xt.b;return e!==Xt?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(s*255)},${Math.round(i*255)})`}offsetHSL(e,t,s){return this.getHSL(di),this.setHSL(di.h+e,di.s+t,di.l+s)}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,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(di),e.getHSL(Io);const s=Pi(di.h,Io.h,t),i=Pi(di.s,Io.s,t),n=Pi(di.l,Io.l,t);return this.setHSL(s,i,n),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,n=e.elements;return this.r=n[0]*t+n[3]*s+n[6]*i,this.g=n[1]*t+n[4]*s+n[7]*i,this.b=n[2]*t+n[5]*s+n[8]*i,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}}const xt=new ve;ve.NAMES=Wm;class ul{constructor(e,t,s,i){ul.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const n=this.elements;return n[0]=e,n[2]=t,n[1]=s,n[3]=i,this}}class gr{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,n,r,a){let l=s[i+0],c=s[i+1],h=s[i+2],u=s[i+3];const d=n[r+0],p=n[r+1],f=n[r+2],m=n[r+3];if(a===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=p,e[t+2]=f,e[t+3]=m;return}if(u!==m||l!==d||c!==p||h!==f){let y=1-a;const g=l*d+c*p+h*f+u*m,_=g>=0?1:-1,b=1-g*g;if(b>Number.EPSILON){const S=Math.sqrt(b),C=Math.atan2(S,g*_);y=Math.sin(y*C)/S,a=Math.sin(a*C)/S}const T=a*_;if(l=l*y+d*T,c=c*y+p*T,h=h*y+f*T,u=u*y+m*T,y===1-a){const S=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=S,c*=S,h*=S,u*=S}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,n,r){const a=s[i],l=s[i+1],c=s[i+2],h=s[i+3],u=n[r],d=n[r+1],p=n[r+2],f=n[r+3];return e[t]=a*f+h*u+l*p-c*d,e[t+1]=l*f+h*d+c*u-a*p,e[t+2]=c*f+h*p+a*d-l*u,e[t+3]=h*f-a*u-l*d-c*p,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,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,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){const s=e._x,i=e._y,n=e._z,r=e._order,a=Math.cos,l=Math.sin,c=a(s/2),h=a(i/2),u=a(n/2),d=l(s/2),p=l(i/2),f=l(n/2);switch(r){case"XYZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"YXZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"ZXY":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"ZYX":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"YZX":this._x=d*h*u+c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u-d*p*f;break;case"XZY":this._x=d*h*u-c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u+d*p*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],n=t[8],r=t[1],a=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=s+a+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(n-c)*p,this._z=(r-i)*p}else if(s>a&&s>u){const p=2*Math.sqrt(1+s-a-u);this._w=(h-l)/p,this._x=.25*p,this._y=(i+r)/p,this._z=(n+c)/p}else if(a>u){const p=2*Math.sqrt(1+a-s-u);this._w=(n-c)/p,this._x=(i+r)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-s-a);this._w=(r-i)/p,this._x=(n+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<Number.EPSILON?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(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=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(pe(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(s===0)return this;const i=Math.min(1,t/s);return this.slerp(e,i),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=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,n=e._z,r=e._w,a=t._x,l=t._y,c=t._z,h=t._w;return this._x=s*h+r*a+i*c-n*l,this._y=i*h+r*l+n*a-s*c,this._z=n*h+r*c+s*l-i*a,this._w=r*h-s*a-i*l-n*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const s=this._x,i=this._y,n=this._z,r=this._w;let a=r*e._w+s*e._x+i*e._y+n*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=r,this._x=s,this._y=i,this._z=n,this;const l=1-a*a;if(l<=Number.EPSILON){const p=1-t;return this._w=p*r+t*this._w,this._x=p*s+t*this._x,this._y=p*i+t*this._y,this._z=p*n+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,a),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=r*u+this._w*d,this._x=s*u+this._x*d,this._y=i*u+this._y*d,this._z=n*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),n=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),n*Math.sin(t),n*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}}class N{constructor(e=0,t=0,s=0){N.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return s===void 0&&(s=this.z),this.x=e,this.y=t,this.z=s,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 new 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 new 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(Ud.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ud.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[3]*s+n[6]*i,this.y=n[1]*t+n[4]*s+n[7]*i,this.z=n[2]*t+n[5]*s+n[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,n=e.elements,r=1/(n[3]*t+n[7]*s+n[11]*i+n[15]);return this.x=(n[0]*t+n[4]*s+n[8]*i+n[12])*r,this.y=(n[1]*t+n[5]*s+n[9]*i+n[13])*r,this.z=(n[2]*t+n[6]*s+n[10]*i+n[14])*r,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,n=e.x,r=e.y,a=e.z,l=e.w,c=2*(r*i-a*s),h=2*(a*t-n*i),u=2*(n*s-r*t);return this.x=t+l*c+r*u-a*h,this.y=s+l*h+a*c-n*u,this.z=i+l*u+n*h-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i,this.y=n[1]*t+n[5]*s+n[9]*i,this.z=n[2]*t+n[6]*s+n[10]*i,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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this.z=pe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this.z=pe(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,n=e.z,r=t.x,a=t.y,l=t.z;return this.x=i*l-n*a,this.y=n*r-s*l,this.z=s*a-i*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Wl.copy(this).projectOnVector(e),this.sub(Wl)}reflect(e){return this.sub(Wl.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(pe(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}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,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,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(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Wl=new N,Ud=new gr;class Ie{constructor(e,t,s,i,n,r,a,l,c,h,u,d,p,f,m,y){Ie.prototype.isMatrix4=!0,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,s,i,n,r,a,l,c,h,u,d,p,f,m,y)}set(e,t,s,i,n,r,a,l,c,h,u,d,p,f,m,y){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=i,g[1]=n,g[5]=r,g[9]=a,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=p,g[7]=f,g[11]=m,g[15]=y,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 Ie().fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const 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,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/vn.setFromMatrixColumn(e,0).length(),n=1/vn.setFromMatrixColumn(e,1).length(),r=1/vn.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*n,t[5]=s[5]*n,t[6]=s[6]*n,t[7]=0,t[8]=s[8]*r,t[9]=s[9]*r,t[10]=s[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,n=e.z,r=Math.cos(s),a=Math.sin(s),l=Math.cos(i),c=Math.sin(i),h=Math.cos(n),u=Math.sin(n);if(e.order==="XYZ"){const d=r*h,p=r*u,f=a*h,m=a*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=p+f*c,t[5]=d-m*c,t[9]=-a*l,t[2]=m-d*c,t[6]=f+p*c,t[10]=r*l}else if(e.order==="YXZ"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d+m*a,t[4]=f*a-p,t[8]=r*c,t[1]=r*u,t[5]=r*h,t[9]=-a,t[2]=p*a-f,t[6]=m+d*a,t[10]=r*l}else if(e.order==="ZXY"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d-m*a,t[4]=-r*u,t[8]=f+p*a,t[1]=p+f*a,t[5]=r*h,t[9]=m-d*a,t[2]=-r*c,t[6]=a,t[10]=r*l}else if(e.order==="ZYX"){const d=r*h,p=r*u,f=a*h,m=a*u;t[0]=l*h,t[4]=f*c-p,t[8]=d*c+m,t[1]=l*u,t[5]=m*c+d,t[9]=p*c-f,t[2]=-c,t[6]=a*l,t[10]=r*l}else if(e.order==="YZX"){const d=r*l,p=r*c,f=a*l,m=a*c;t[0]=l*h,t[4]=m-d*u,t[8]=f*u+p,t[1]=u,t[5]=r*h,t[9]=-a*h,t[2]=-c*h,t[6]=p*u+f,t[10]=d-m*u}else if(e.order==="XZY"){const d=r*l,p=r*c,f=a*l,m=a*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+m,t[5]=r*h,t[9]=p*u-f,t[2]=f*u-p,t[6]=a*h,t[10]=m*u+d}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(I_,e,L_)}lookAt(e,t,s){const i=this.elements;return Wt.subVectors(e,t),Wt.lengthSq()===0&&(Wt.z=1),Wt.normalize(),pi.crossVectors(s,Wt),pi.lengthSq()===0&&(Math.abs(s.z)===1?Wt.x+=1e-4:Wt.z+=1e-4,Wt.normalize(),pi.crossVectors(s,Wt)),pi.normalize(),Lo.crossVectors(Wt,pi),i[0]=pi.x,i[4]=Lo.x,i[8]=Wt.x,i[1]=pi.y,i[5]=Lo.y,i[9]=Wt.y,i[2]=pi.z,i[6]=Lo.z,i[10]=Wt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,n=this.elements,r=s[0],a=s[4],l=s[8],c=s[12],h=s[1],u=s[5],d=s[9],p=s[13],f=s[2],m=s[6],y=s[10],g=s[14],_=s[3],b=s[7],T=s[11],S=s[15],C=i[0],w=i[4],R=i[8],P=i[12],z=i[1],$=i[5],q=i[9],j=i[13],X=i[2],Z=i[6],we=i[10],ue=i[14],ye=i[3],se=i[7],Me=i[11],ze=i[15];return n[0]=r*C+a*z+l*X+c*ye,n[4]=r*w+a*$+l*Z+c*se,n[8]=r*R+a*q+l*we+c*Me,n[12]=r*P+a*j+l*ue+c*ze,n[1]=h*C+u*z+d*X+p*ye,n[5]=h*w+u*$+d*Z+p*se,n[9]=h*R+u*q+d*we+p*Me,n[13]=h*P+u*j+d*ue+p*ze,n[2]=f*C+m*z+y*X+g*ye,n[6]=f*w+m*$+y*Z+g*se,n[10]=f*R+m*q+y*we+g*Me,n[14]=f*P+m*j+y*ue+g*ze,n[3]=_*C+b*z+T*X+S*ye,n[7]=_*w+b*$+T*Z+S*se,n[11]=_*R+b*q+T*we+S*Me,n[15]=_*P+b*j+T*ue+S*ze,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],s=e[4],i=e[8],n=e[12],r=e[1],a=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14],f=e[3],m=e[7],y=e[11],g=e[15];return f*(+n*l*u-i*c*u-n*a*d+s*c*d+i*a*p-s*l*p)+m*(+t*l*p-t*c*d+n*r*d-i*r*p+i*c*h-n*l*h)+y*(+t*c*u-t*a*p-n*r*u+s*r*p+n*a*h-s*c*h)+g*(-i*a*h-t*l*u+t*a*d+i*r*u-s*r*d+s*l*h)}transpose(){const e=this.elements;let 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,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],y=e[14],g=e[15],_=u*y*c-m*d*c+m*l*p-a*y*p-u*l*g+a*d*g,b=f*d*c-h*y*c-f*l*p+r*y*p+h*l*g-r*d*g,T=h*m*c-f*u*c+f*a*p-r*m*p-h*a*g+r*u*g,S=f*u*l-h*m*l-f*a*d+r*m*d+h*a*y-r*u*y,C=t*_+s*b+i*T+n*S;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/C;return e[0]=_*w,e[1]=(m*d*n-u*y*n-m*i*p+s*y*p+u*i*g-s*d*g)*w,e[2]=(a*y*n-m*l*n+m*i*c-s*y*c-a*i*g+s*l*g)*w,e[3]=(u*l*n-a*d*n-u*i*c+s*d*c+a*i*p-s*l*p)*w,e[4]=b*w,e[5]=(h*y*n-f*d*n+f*i*p-t*y*p-h*i*g+t*d*g)*w,e[6]=(f*l*n-r*y*n-f*i*c+t*y*c+r*i*g-t*l*g)*w,e[7]=(r*d*n-h*l*n+h*i*c-t*d*c-r*i*p+t*l*p)*w,e[8]=T*w,e[9]=(f*u*n-h*m*n-f*s*p+t*m*p+h*s*g-t*u*g)*w,e[10]=(r*m*n-f*a*n+f*s*c-t*m*c-r*s*g+t*a*g)*w,e[11]=(h*a*n-r*u*n-h*s*c+t*u*c+r*s*p-t*a*p)*w,e[12]=S*w,e[13]=(h*m*i-f*u*i+f*s*d-t*m*d-h*s*y+t*u*y)*w,e[14]=(f*a*i-r*m*i-f*s*l+t*m*l+r*s*y-t*a*y)*w,e[15]=(r*u*i-h*a*i+h*s*l-t*u*l-r*s*d+t*a*d)*w,this}scale(e){const t=this.elements,s=e.x,i=e.y,n=e.z;return t[0]*=s,t[4]*=i,t[8]*=n,t[1]*=s,t[5]*=i,t[9]*=n,t[2]*=s,t[6]*=i,t[10]*=n,t[3]*=s,t[7]*=i,t[11]*=n,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){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,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),n=1-s,r=e.x,a=e.y,l=e.z,c=n*r,h=n*a;return this.set(c*r+s,c*a-i*l,c*l+i*a,0,c*a+i*l,h*a+s,h*l-i*r,0,c*l-i*a,h*l+i*r,n*l*l+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,n,r){return this.set(1,s,n,0,e,1,r,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,n=t._x,r=t._y,a=t._z,l=t._w,c=n+n,h=r+r,u=a+a,d=n*c,p=n*h,f=n*u,m=r*h,y=r*u,g=a*u,_=l*c,b=l*h,T=l*u,S=s.x,C=s.y,w=s.z;return i[0]=(1-(m+g))*S,i[1]=(p+T)*S,i[2]=(f-b)*S,i[3]=0,i[4]=(p-T)*C,i[5]=(1-(d+g))*C,i[6]=(y+_)*C,i[7]=0,i[8]=(f+b)*w,i[9]=(y-_)*w,i[10]=(1-(d+m))*w,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let n=vn.set(i[0],i[1],i[2]).length();const r=vn.set(i[4],i[5],i[6]).length(),a=vn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),e.x=i[12],e.y=i[13],e.z=i[14],ps.copy(this);const c=1/n,h=1/r,u=1/a;return ps.elements[0]*=c,ps.elements[1]*=c,ps.elements[2]*=c,ps.elements[4]*=h,ps.elements[5]*=h,ps.elements[6]*=h,ps.elements[8]*=u,ps.elements[9]*=u,ps.elements[10]*=u,t.setFromRotationMatrix(ps),s.x=n,s.y=r,s.z=a,this}makePerspective(e,t,s,i,n,r,a=Ut){const l=this.elements,c=2*n/(t-e),h=2*n/(s-i),u=(t+e)/(t-e),d=(s+i)/(s-i);let p,f;if(a===Ut)p=-(r+n)/(r-n),f=-2*r*n/(r-n);else if(a===Oi)p=-r/(r-n),f=-r*n/(r-n);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,i,n,r,a=Ut){const l=this.elements,c=1/(t-e),h=1/(s-i),u=1/(r-n),d=(t+e)*c,p=(s+i)*h;let f,m;if(a===Ut)f=(r+n)*u,m=-2*u;else if(a===Oi)f=n*u,m=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=m,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<16;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const vn=new N,ps=new Ie,I_=new N(0,0,0),L_=new N(1,1,1),pi=new N,Lo=new N,Wt=new N;class ce{constructor(e=0,t=0){ce.prototype.isVector2=!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 new 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 new 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){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(pe(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,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){const s=Math.cos(t),i=Math.sin(t),n=this.x-e.x,r=this.y-e.y;return this.x=n*s-r*i+e.x,this.y=n*i+r*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ge{constructor(e=0,t=0,s=0,i=1){ge.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}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,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,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 new 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 new 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?e.w:1,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){const t=this.x,s=this.y,i=this.z,n=this.w,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i+r[12]*n,this.y=r[1]*t+r[5]*s+r[9]*i+r[13]*n,this.z=r[2]*t+r[6]*s+r[10]*i+r[14]*n,this.w=r[3]*t+r[7]*s+r[11]*i+r[15]*n,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);const 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,s,i,n;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],f=l[9],m=l[2],y=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(f-y)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(f+y)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const b=(c+1)/2,T=(p+1)/2,S=(g+1)/2,C=(h+d)/4,w=(u+m)/4,R=(f+y)/4;return b>T&&b>S?b<.01?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(b),i=C/s,n=w/s):T>S?T<.01?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(T),s=C/i,n=R/i):S<.01?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(S),s=w/n,i=R/n),this.set(s,i,n,t),this}let _=Math.sqrt((y-f)*(y-f)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(y-f)/_,this.y=(u-m)/_,this.z=(d-h)/_,this.w=Math.acos((c+p+g-1)/2),this}setFromMatrixPosition(e){const 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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this.z=pe(this.z,e.z,t.z),this.w=pe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this.z=pe(this.z,e,t),this.w=pe(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,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}}function _o(o,e=0){let t=3735928559^e,s=1103547991^e;if(o instanceof Array)for(let i=0,n;i<o.length;i++)n=o[i],t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);else for(let i=0,n;i<o.length;i++)n=o.charCodeAt(i),t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&s)+(t>>>0)}const U_=o=>_o(o),lu=o=>_o(o),Ka=(...o)=>_o(o);function $m(o,e=!1){const t=[];o.isNode===!0&&(t.push(o.id),o=o.getSelf());for(const{property:s,childNode:i}of Ja(o))t.push(_o(s.slice(0,-4)),i.getCacheKey(e));return _o(t)}function*Ja(o,e=!1){for(const t in o){if(t.startsWith("_")===!0)continue;const s=o[t];if(Array.isArray(s)===!0)for(let i=0;i<s.length;i++){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}else if(s&&s.isNode===!0)yield{property:t,childNode:s};else if(typeof s=="object")for(const i in s){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}}}const k_=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),kd=new WeakMap;function z_(o){return k_.get(o)}function el(o){if(o==null)return null;const e=typeof o;return o.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":o.isVector2===!0?"vec2":o.isVector3===!0?"vec3":o.isVector4===!0?"vec4":o.isMatrix2===!0?"mat2":o.isMatrix3===!0?"mat3":o.isMatrix4===!0?"mat4":o.isColor===!0?"color":o instanceof ArrayBuffer?"ArrayBuffer":null}function jm(o,...e){const t=o?o.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),o==="color"?new ve(...e):t==="vec2"?new ce(...e):t==="vec3"?new N(...e):t==="vec4"?new ge(...e):t==="mat2"?new ul(...e):t==="mat3"?new Ht(...e):t==="mat4"?new Ie(...e):o==="bool"?e[0]||!1:o==="float"||o==="int"||o==="uint"?e[0]||0:o==="string"?e[0]||"":o==="ArrayBuffer"?G_(e[0]):null}function qm(o){let e=kd.get(o);return e===void 0&&(e={},kd.set(o,e)),e}function V_(o){let e="";const t=new Uint8Array(o);for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e)}function G_(o){return Uint8Array.from(atob(o),e=>e.charCodeAt(0)).buffer}let H_=0;function W_(o){const e=Object.keys(o);let t=Object.getPrototypeOf(o);for(;t;){const s=Object.getOwnPropertyDescriptors(t);for(const i in s)if(s[i]!==void 0){const n=s[i];n&&typeof n.get=="function"&&e.push(i)}t=Object.getPrototypeOf(t)}return e}class $_{constructor(e,t,s,i,n,r,a,l,c,h){this.id=H_++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=n,this.scene=r,this.camera=a,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=n.version,this.drawRange=null,this.attributes=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=h,this.clippingContextCacheKey=h!==null?h.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.material.hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const n of e){const r=n.node&&n.node.attribute?n.node.attribute:t.getAttribute(n.name);if(r===void 0)continue;s.push(r);const a=r.isInterleavedBufferAttribute?r.data:r;i.add(a)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:n}=this,r=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),l=a!==null;let c=1;if(s.isInstancedBufferGeometry===!0?c=s.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(r.instanceCount=c,e.isBatchedMesh===!0)return r;let h=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(h=2);let u=n.start*h,d=(n.start+n.count)*h;i!==null&&(u=Math.max(u,i.start*h),d=Math.min(d,(i.start+i.count)*h));const p=s.attributes.position;let f=1/0;l?f=a.count:p!=null&&(f=p.count),u=Math.max(u,0),d=Math.min(d,f);const m=d-u;return m<0||m===1/0?null:(r.vertexCount=m,r.firstVertex=u,r)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let n=0,r=i.length;n<r;n++){const a=i[n];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const i of W_(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(i))continue;const n=t[i];let r;if(n!==null){const a=typeof n;a==="number"?r=n!==0?"1":"0":a==="object"?(r="{",n.isTexture&&(r+=n.mapping),r+="}"):r=String(n)}else r=String(n);s+=r+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",U_(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Ka(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ka(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const Vi=[];class j_{constructor(e,t,s,i,n,r){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=n,this.info=r,this.chainMaps={}}get(e,t,s,i,n,r,a,l){const c=this.getChainMap(l);Vi[0]=e,Vi[1]=t,Vi[2]=r,Vi[3]=n;let h=c.get(Vi);return h===void 0?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,n,r,a,l),c.set(Vi,h)):(h.updateClipping(a),h.needsGeometryUpdate&&h.setGeometry(e.geometry),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,n,r,a,l)):h.version=t.version)),Vi.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,n,r,a,l,c,h,u){const d=this.getChainMap(u),p=new $_(e,t,s,i,n,r,a,l,c,h);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.delete(p),this.nodes.delete(p),d.delete(p.getChainArray())},p}}class Li{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const as={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},Ci=16,q_=211,Y_=212;class X_ extends Li{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return t!==null&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(s.version===void 0)t===as.VERTEX?this.backend.createAttribute(e):t===as.INDEX?this.backend.createIndexAttribute(e):t===as.STORAGE?this.backend.createStorageAttribute(e):t===as.INDIRECT&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(s.version<i.version||i.usage===jn)&&(this.backend.updateAttribute(e),s.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const Ys=Z_();function Z_(){const o=new ArrayBuffer(4),e=new Float32Array(o),t=new Uint32Array(o),s=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(s[l]=0,s[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(s[l]=1024>>-c-14,s[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(s[l]=c+15<<10,s[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(s[l]=31744,s[l|256]=64512,i[l]=24,i[l|256]=24):(s[l]=31744,s[l|256]=64512,i[l]=13,i[l|256]=13)}const n=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,n[l]=c|h}for(let l=1024;l<2048;++l)n[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(a[l]=1024);return{floatView:e,uint32View:t,baseTable:s,shiftTable:i,mantissaTable:n,exponentTable:r,offsetTable:a}}function $t(o){Math.abs(o)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),o=pe(o,-65504,65504),Ys.floatView[0]=o;const e=Ys.uint32View[0],t=e>>23&511;return Ys.baseTable[t]+((e&8388607)>>Ys.shiftTable[t])}function Uo(o){const e=o>>10;return Ys.uint32View[0]=Ys.mantissaTable[Ys.offsetTable[e]+(o&1023)]+Ys.exponentTable[e],Ys.floatView[0]}const Ke=new N,ko=new ce;let Q_=0;class ls{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Q_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=Qa,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,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,n=this.itemSize;i<n;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,s=this.count;t<s;t++)ko.fromBufferAttribute(this,t),ko.applyMatrix3(e),this.setXY(t,ko.x,ko.y);else if(this.itemSize===3)for(let t=0,s=this.count;t<s;t++)Ke.fromBufferAttribute(this,t),Ke.applyMatrix3(e),this.setXYZ(t,Ke.x,Ke.y,Ke.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Ke.fromBufferAttribute(this,t),Ke.applyMatrix4(e),this.setXYZ(t,Ke.x,Ke.y,Ke.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Ke.fromBufferAttribute(this,t),Ke.applyNormalMatrix(e),this.setXYZ(t,Ke.x,Ke.y,Ke.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Ke.fromBufferAttribute(this,t),Ke.transformDirection(e),this.setXYZ(t,Ke.x,Ke.y,Ke.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=ae(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=n,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const 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!==Qa&&(e.usage=this.usage),e}}class Ym extends ls{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Xm extends ls{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Zm extends ls{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Uo(this.array[e*this.itemSize]);return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize]=$t(t),this}getY(e){let t=Uo(this.array[e*this.itemSize+1]);return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+1]=$t(t),this}getZ(e){let t=Uo(this.array[e*this.itemSize+2]);return this.normalized&&(t=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+2]=$t(t),this}getW(e){let t=Uo(this.array[e*this.itemSize+3]);return this.normalized&&(t=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+3]=$t(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this.array[e+2]=$t(i),this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this.array[e+2]=$t(i),this.array[e+3]=$t(n),this}}class Pt extends ls{constructor(e,t,s){super(new Float32Array(e),t,s)}}function Qm(o){return o.index!==null?o.index.version:o.attributes.position.version}function zd(o){const e=[],t=o.index,s=o.attributes.position;if(t!==null){const n=t.array;for(let r=0,a=n.length;r<a;r+=3){const l=n[r+0],c=n[r+1],h=n[r+2];e.push(l,c,c,h,h,l)}}else{const n=s.array;for(let r=0,a=n.length/3-1;r<a;r+=3){const l=r+0,c=r+1,h=r+2;e.push(l,c,c,h,h,l)}}const i=new(Hm(e)?Xm:Ym)(e,1);return i.version=Qm(o),i}class K_ extends Li{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,s=this.get(t);s.initialized=!0,this.info.memory.geometries++;const i=()=>{this.info.memory.geometries--;const n=t.index,r=e.getAttributes();n!==null&&this.attributes.delete(n);for(const l of r)this.attributes.delete(l);const a=this.wireframes.get(t);a!==void 0&&this.attributes.delete(a),t.removeEventListener("dispose",i)};t.addEventListener("dispose",i)}updateAttributes(e){const t=e.getAttributes();for(const n of t)n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute?this.updateAttribute(n,as.STORAGE):this.updateAttribute(n,as.VERTEX);const s=this.getIndex(e);s!==null&&this.updateAttribute(s,as.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,as.INDIRECT)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(s.wireframe===!0){const n=this.wireframes;let r=n.get(t);r===void 0?(r=zd(t),n.set(t,r)):r.version!==Qm(t)&&(this.attributes.delete(r),r=zd(t),n.set(t,r)),i=r}return i}}class J_{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Km{constructor(e){this.cacheKey=e,this.usedTimes=0}}class eb extends Km{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class tb extends Km{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let sb=0;class $l{constructor(e,t,s,i=null,n=null){this.id=sb++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=n,this.usedTimes=0}}class ib extends Li{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.computeProgram.usedTimes--);const r=this.nodes.getForCompute(e);let a=this.programs.compute.get(r.computeShader);a===void 0&&(n&&n.computeProgram.usedTimes===0&&this._releaseProgram(n.computeProgram),a=new $l(r.computeShader,"compute",e.name,r.transforms,r.nodeAttributes),this.programs.compute.set(r.computeShader,a),s.createProgram(a));const l=this._getComputeCacheKey(e,a);let c=this.caches.get(l);c===void 0&&(n&&n.usedTimes===0&&this._releasePipeline(n),c=this._getComputePipeline(e,a,l,t)),c.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=c}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.vertexProgram.usedTimes--,n.fragmentProgram.usedTimes--);const r=e.getNodeBuilderState(),a=e.material?e.material.name:"";let l=this.programs.vertex.get(r.vertexShader);l===void 0&&(n&&n.vertexProgram.usedTimes===0&&this._releaseProgram(n.vertexProgram),l=new $l(r.vertexShader,"vertex",a),this.programs.vertex.set(r.vertexShader,l),s.createProgram(l));let c=this.programs.fragment.get(r.fragmentShader);c===void 0&&(n&&n.fragmentProgram.usedTimes===0&&this._releaseProgram(n.fragmentProgram),c=new $l(r.fragmentShader,"fragment",a),this.programs.fragment.set(r.fragmentShader,c),s.createProgram(c));const h=this._getRenderCacheKey(e,l,c);let u=this.caches.get(h);u===void 0?(n&&n.usedTimes===0&&this._releasePipeline(n),u=this._getRenderPipeline(e,l,c,h,t)):e.pipeline=u,u.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=u}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let n=this.caches.get(s);return n===void 0&&(n=new tb(s,t),this.caches.set(s,n),this.backend.createComputePipeline(n,i)),n}_getRenderPipeline(e,t,s,i,n){i=i||this._getRenderCacheKey(e,t,s);let r=this.caches.get(i);return r===void 0&&(r=new eb(i,t,s),this.caches.set(i,r),e.pipeline=r,this.backend.createRenderPipeline(e,n)),r}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class nb extends Li{constructor(e,t,s,i,n,r){super(),this.backend=e,this.textures=s,this.pipelines=n,this.attributes=i,this.nodes=t,this.info=r,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const s=t.attribute,i=s.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(s,i)}}_update(e,t){const{backend:s}=this;let i=!1,n=!0,r=0,a=0;for(const l of e.bindings)if(!(l.isNodeUniformsGroup&&this.nodes.updateGroup(l)===!1)){if(l.isStorageBuffer){const c=l.attribute,h=c.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(c,h)}if(l.isUniformBuffer)l.update()&&s.updateBinding(l);else if(l.isSampler)l.update();else if(l.isSampledTexture){const c=this.textures.get(l.texture);l.needsBindingsUpdate(c.generation)&&(i=!0);const h=l.update(),u=l.texture;h&&this.textures.updateTexture(u);const d=s.get(u);if(d.externalTexture!==void 0||c.isDefaultTexture?n=!1:(r=r*10+u.id,a+=u.version),s.isWebGPUBackend===!0&&d.texture===void 0&&d.externalTexture===void 0&&(console.error("Bindings._update: binding should be available:",l,h,u,l.textureNode.value,i),this.textures.updateTexture(u),i=!0),u.isStorageTexture===!0){const p=this.get(u);l.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(u)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(u),p.needsMipmap=!1)}}}i===!0&&this.backend.updateBindings(e,t,n?r:0,a)}}function rb(o,e){return o.groupOrder!==e.groupOrder?o.groupOrder-e.groupOrder:o.renderOrder!==e.renderOrder?o.renderOrder-e.renderOrder:o.z!==e.z?o.z-e.z:o.id-e.id}function Vd(o,e){return o.groupOrder!==e.groupOrder?o.groupOrder-e.groupOrder:o.renderOrder!==e.renderOrder?o.renderOrder-e.renderOrder:o.z!==e.z?e.z-o.z:o.id-e.id}function Gd(o){return(o.transmission>0||o.transmissionNode)&&o.side===Qn&&o.forceSinglePass===!1}class ob{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,n,r,a){let l=this.renderItems[this.renderItemsIndex];return l===void 0?(l={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:n,group:r,clippingContext:a},this.renderItems[this.renderItemsIndex]=l):(l.id=e.id,l.object=e,l.geometry=t,l.material=s,l.groupOrder=i,l.renderOrder=e.renderOrder,l.z=n,l.group=r,l.clippingContext=a),this.renderItemsIndex++,l}push(e,t,s,i,n,r,a){const l=this.getNextRenderItem(e,t,s,i,n,r,a);e.occlusionTest===!0&&this.occlusionQueryCount++,s.transparent===!0||s.transmission>0?(Gd(s)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,s,i,n,r,a){const l=this.getNextRenderItem(e,t,s,i,n,r,a);s.transparent===!0||s.transmission>0?(Gd(s)&&this.transparentDoublePass.unshift(l),this.transparent.unshift(l)):this.opaque.unshift(l)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||rb),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Vd),this.transparent.length>1&&this.transparent.sort(t||Vd)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const s=this.renderItems[e];if(s.id===null)break;s.id=null,s.object=null,s.geometry=null,s.material=null,s.groupOrder=null,s.renderOrder=null,s.z=null,s.group=null,s.clippingContext=null}}}const Mr=[];class ab{constructor(e){this.lighting=e,this.lists=new vs}get(e,t){const s=this.lists;Mr[0]=e,Mr[1]=t;let i=s.get(Mr);return i===void 0&&(i=new ob(this.lighting,e,t),s.set(Mr,i)),Mr.length=0,i}dispose(){this.lists=new vs}}let lb=0;class cb{constructor(){this.id=lb++,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new ge,this.scissor=!1,this.scissorValue=new ge,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return Jm(this)}}function Jm(o){const{textures:e,activeCubeFace:t}=o,s=[t];for(const i of e)s.push(i.id);return lu(s)}let pn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,r=i.length;n<r;n++)i[n].call(this,e);e.target=null}}};const Hd=new Ie,Wd=new gr;class us{constructor(e=0,t=0,s=0,i=us.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,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,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,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,s=!0){const i=e.elements,n=i[0],r=i[4],a=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(pe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-pe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,n),this._z=0);break;case"ZXY":this._x=Math.asin(pe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,n));break;case"ZYX":this._y=Math.asin(-pe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,n)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(pe(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,n)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-pe(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return Hd.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Hd,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Wd.setFromEuler(this),this.setFromQuaternion(Wd,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}}us.DEFAULT_ORDER="XYZ";class hb{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}}let ub=0;const $d=new N,wn=new gr,Gs=new Ie,zo=new N,Cr=new N,db=new N,pb=new gr,jd=new N(1,0,0),qd=new N(0,1,0),Yd=new N(0,0,1),Xd={type:"added"},fb={type:"removed"},Mn={type:"childadded",child:null},jl={type:"childremoved",child:null};class dt extends pn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:ub++}),this.uuid=Qs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=dt.DEFAULT_UP.clone();const e=new N,t=new us,s=new gr,i=new N(1,1,1);function n(){s.setFromEuler(t,!1)}function r(){t.setFromQuaternion(s,void 0,!1)}t._onChange(n),s._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ie},normalMatrix:{value:new Ht}}),this.matrix=new Ie,this.matrixWorld=new Ie,this.matrixAutoUpdate=dt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new hb,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.userData={}}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 wn.setFromAxisAngle(e,t),this.quaternion.multiply(wn),this}rotateOnWorldAxis(e,t){return wn.setFromAxisAngle(e,t),this.quaternion.premultiply(wn),this}rotateX(e){return this.rotateOnAxis(jd,e)}rotateY(e){return this.rotateOnAxis(qd,e)}rotateZ(e){return this.rotateOnAxis(Yd,e)}translateOnAxis(e,t){return $d.copy(e).applyQuaternion(this.quaternion),this.position.add($d.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(jd,e)}translateY(e){return this.translateOnAxis(qd,e)}translateZ(e){return this.translateOnAxis(Yd,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Gs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?zo.copy(e):zo.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Cr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Gs.lookAt(Cr,zo,this.up):Gs.lookAt(zo,Cr,this.up),this.quaternion.setFromRotationMatrix(Gs),i&&(Gs.extractRotation(i.matrixWorld),wn.setFromRotationMatrix(Gs),this.quaternion.premultiply(wn.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.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(Xd),Mn.child=e,this.dispatchEvent(Mn),Mn.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.remove(arguments[s]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(fb),jl.child=e,this.dispatchEvent(jl),jl.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Gs.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Gs.multiply(e.parent.matrixWorld)),e.applyMatrix4(Gs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Xd),Mn.child=e,this.dispatchEvent(Mn),Mn.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 s=0,i=this.children.length;s<i;s++){const r=this.children[s].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let n=0,r=i.length;n<r;n++)i[n].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cr,e,db),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Cr,pb,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),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);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}updateWorldMatrix(e,t){const s=this.parent;if(e===!0&&s!==null&&s.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){const i=this.children;for(let n=0,r=i.length;n<r;n++)i[n].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function n(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=n(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];n(e.shapes,u)}else n(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(n(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let l=0,c=this.material.length;l<c;l++)a.push(n(e.materials,this.material[l]));i.material=a}else i.material=n(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){const l=this.animations[a];i.animations.push(n(e.animations,l))}}if(t){const a=r(e.geometries),l=r(e.materials),c=r(e.textures),h=r(e.images),u=r(e.shapes),d=r(e.skeletons),p=r(e.animations),f=r(e.nodes);a.length>0&&(s.geometries=a),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),h.length>0&&(s.images=h),u.length>0&&(s.shapes=u),d.length>0&&(s.skeletons=d),p.length>0&&(s.animations=p),f.length>0&&(s.nodes=f)}return s.object=i,s;function r(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}}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.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.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let s=0;s<e.children.length;s++){const i=e.children[s];this.add(i.clone())}return this}}dt.DEFAULT_UP=new N(0,1,0);dt.DEFAULT_MATRIX_AUTO_UPDATE=!0;dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class cu extends dt{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 us,this.environmentIntensity=1,this.environmentRotation=new us,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){const 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}}class hu extends dt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ie,this.projectionMatrix=new Ie,this.projectionMatrixInverse=new Ie,this.coordinateSystem=Ut}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Er=[],mb=new cu,gb=new hu;class yb{constructor(){this.chainMaps={}}get(e,t,s=null){Er[0]=e,Er[1]=t;let i;if(s===null)i="default";else{const a=s.texture.format;i=`${s.textures.length}:${a}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this._getChainMap(i);let r=n.get(Er);return r===void 0&&(r=new cb,n.set(Er,r)),Er.length=0,s!==null&&(r.sampleCount=s.samples===0?1:s.samples),r}getForClear(e=null){return this.get(mb,gb,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}}let Cn;class xb{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{Cn===void 0&&(Cn=Dh("canvas")),Cn.width=e.width,Cn.height=e.height;const i=Cn.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),s=Cn}return s.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Dh("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),n=i.data;for(let r=0;r<n.length;r++)n[r]=si(n[r]/255)*255;return s.putImageData(i,0,0),t}else if(e.data){const t=e.data.slice(0);for(let s=0;s<t.length;s++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[s]=Math.floor(si(t[s]/255)*255):t[s]=si(t[s]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let _b=0;class uu{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:_b++}),this.uuid=Qs(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(i!==null){let n;if(Array.isArray(i)){n=[];for(let r=0,a=i.length;r<a;r++)i[r].isDataTexture?n.push(ql(i[r].image)):n.push(ql(i[r]))}else n=ql(i);s.url=n}return t||(e.images[this.uuid]=s),s}}function ql(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?xb.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let bb=0;const Yl=new N;class St extends pn{constructor(e=St.DEFAULT_IMAGE,t=St.DEFAULT_MAPPING,s=Ri,i=Ri,n=Kt,r=ei,a=os,l=Nt,c=St.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:bb++}),this.uuid=Qs(),this.name="",this.source=new uu(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=n,this.minFilter=r,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=l,this.offset=new ce(0,0),this.repeat=new ce(1,1),this.center=new ce(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ht,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Yl).x}get height(){return this.source.getSize(Yl).y}get depth(){return this.source.getSize(Yl).z}get image(){return this.source.data}set image(e=null){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.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(const t in e){const s=e[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const s={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,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&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Jh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case cr:e.x=e.x-Math.floor(e.x);break;case Ri:e.x=e.x<0?0:1;break;case hr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case cr:e.y=e.y-Math.floor(e.y);break;case Ri:e.y=e.y<0?0:1;break;case hr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-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++}}St.DEFAULT_IMAGE=null;St.DEFAULT_MAPPING=Jh;St.DEFAULT_ANISOTROPY=1;class Is extends St{constructor(e,t,s=Xe,i,n,r,a=ut,l=ut,c,h=Bs,u=1){if(h!==Bs&&h!==ti)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:u};super(d,i,n,r,a,l,h,s,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new uu(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const Tb=new N;class Sb extends Li{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=e.samples===0?1:e.samples,n=s.depthTextureMips||(s.depthTextureMips={}),r=e.textures,a=this.getSize(r[0]),l=a.width>>t,c=a.height>>t;let h=e.depthTexture||n[t];const u=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;h===void 0&&u&&(h=new Is,h.format=e.stencilBuffer?ti:Bs,h.type=e.stencilBuffer?Fi:Xe,h.image.width=l,h.image.height=c,h.image.depth=a.depth,h.isArrayTexture=e.multiview===!0&&a.depth>1,n[t]=h),(s.width!==a.width||a.height!==s.height)&&(d=!0,h&&(h.needsUpdate=!0,h.image.width=l,h.image.height=c,h.image.depth=h.isArrayTexture?h.image.depth:1)),s.width=a.width,s.height=a.height,s.textures=r,s.depthTexture=h||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(d=!0,h&&(h.needsUpdate=!0),s.sampleCount=i);const p={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let f=0;f<r.length;f++){const m=r[f];d&&(m.needsUpdate=!0),this.updateTexture(m,p)}h&&this.updateTexture(h,p)}if(s.initialized!==!0){s.initialized=!0;const f=()=>{e.removeEventListener("dispose",f);for(let m=0;m<r.length;m++)this._destroyTexture(r[m]);h&&this._destroyTexture(h),this.delete(e)};e.addEventListener("dispose",f)}}updateTexture(e,t={}){const s=this.get(e);if(s.initialized===!0&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,n=this.backend;if(i&&s.initialized===!0&&(n.destroySampler(e),n.destroyTexture(e)),e.isFramebufferTexture){const c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=Nt}const{width:r,height:a,depth:l}=this.getSize(e);if(t.width=r,t.height=a,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,r,a):1,i||e.isStorageTexture===!0)n.createSampler(e),n.createTexture(e,t),s.generation=e.version;else if(s.initialized!==!0&&n.createSampler(e),e.version>0){const h=e.image;if(h===void 0)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(h.complete===!1)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const u=[];for(const d of e.images)u.push(d);t.images=u}else t.image=h;(s.isDefaultTexture===void 0||s.isDefaultTexture===!0)&&(n.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),e.source.dataReady===!0&&n.updateTexture(e,t),t.needsMipmaps&&e.mipmaps.length===0&&n.generateMipmaps(e)}}else n.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;if(s.initialized!==!0){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const c=()=>{e.removeEventListener("dispose",c),this._destroyTexture(e)};e.addEventListener("dispose",c)}s.version=e.version}getSize(e,t=Tb){let s=e.images?e.images[0]:e.image;return s?(s.image!==void 0&&(s=s.image),t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return e.isCompressedTexture?e.mipmaps?i=e.mipmaps.length:i=1:i=Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return e.isCompressedTexture===!0||e.generateMipmaps}_destroyTexture(e){this.has(e)===!0&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class du extends ve{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const Vo={VERTEX:"vertex"},he={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Zs={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},vb=["fragment","vertex"],Zd=["setup","analyze","generate"],Qd=[...vb,"compute"],yr=["x","y","z","w"],wb={analyze:"setup",generate:"analyze"};let Mb=0;class re extends pn{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=he.NONE,this.updateBeforeType=he.NONE,this.updateAfterType=he.NONE,this.uuid=Fx.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Mb++})}set needsUpdate(e){e===!0&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,he.FRAME)}onRenderUpdate(e){return this.onUpdate(e,he.RENDER)}onObjectUpdate(e){return this.onUpdate(e,he.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Ja(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return e=e||this.version!==this._cacheKeyVersion,(e===!0||this._cacheKey===null)&&(this._cacheKey=Ka($m(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())t["node"+s++]=i;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(this.parents===!0){const i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(s===1){const i=e.getNodeProperties(this);for(const n of Object.values(i))n&&n.isNode===!0&&n.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&s.isNode===!0)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const n=wb[e.buildStage];if(n&&i.buildStages[n]!==!0){const l=e.getBuildStage();e.setBuildStage(n),this.build(e),e.setBuildStage(l)}e.addNode(this),e.addChain(this);let r=null;const a=e.getBuildStage();if(a==="setup"){this.updateReference(e);const l=e.getNodeProperties(this);if(l.initialized!==!0){l.initialized=!0,l.outputNode=this.setup(e)||l.outputNode||null;for(const c of Object.values(l))if(c&&c.isNode===!0){if(c.parents===!0){const h=e.getNodeProperties(c);h.parents=h.parents||[],h.parents.push(this)}c.build(e)}}r=l.outputNode}else if(a==="analyze")this.analyze(e,t);else if(a==="generate")if(this.generate.length===1){const c=this.getNodeType(e),h=e.getDataFromNode(this);r=h.snippet,r===void 0?h.generated===void 0?(h.generated=!0,r=this.generate(e)||"",h.snippet=r):(console.warn("THREE.Node: Recursion detected.",this),r=""):h.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),r=e.format(r,c,t)}else r=this.generate(e,t)||"";return e.removeChain(this),e.addSequentialNode(this),r}getSerializeChildren(){return Ja(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:n,childNode:r}of t)n!==void 0?(s[i]===void 0&&(s[i]=Number.isInteger(n)?[]:{}),s[i][n]=r.toJSON(e.meta).uuid):s[i]=r.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const n of e.inputNodes[s])i.push(t[n]);this[s]=i}else if(typeof e.inputNodes[s]=="object"){const i={};for(const n in e.inputNodes[s]){const r=e.inputNodes[s][n];i[n]=t[r]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let n=e.nodes[t];n===void 0&&(n={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[n.uuid]=n),this.serialize(n),delete n.meta);function r(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}if(i){const a=r(e.textures),l=r(e.images),c=r(e.nodes);a.length>0&&(n.textures=a),l.length>0&&(n.images=l),c.length>0&&(n.nodes=c)}return n}}class nt extends re{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){const i=e.getVectorType(this.getNodeType(e,t)),n=e.getDataFromNode(this);if(n.propertyName!==void 0)return e.format(n.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){const r=super.build(e,i),a=e.getVarFromNode(this,null,i),l=e.getPropertyName(a);return e.addLineFlowCode(`${l} = ${r}`,this),n.snippet=r,n.propertyName=l,e.format(n.propertyName,i,t)}}return super.build(e,t)}}class Mo extends re{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e),s=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${s}[ ${i} ]`}}class eg extends re{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))(s===null||e.getTypeLength(t)===e.getTypeLength(i))&&(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),n=s.build(e,i);return e.format(n,i,t)}}class Cb extends nt{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),n=this.nodes,r=e.getComponentType(s),a=[];let l=0;for(const h of n){if(l>=i){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let u=h.getNodeType(e),d=e.getTypeLength(u),p;l+d>i&&(console.error(`THREE.TSL: Length of '${s}()' data exceeds maximum length of output type.`),d=i-l,u=e.getTypeFromLength(d)),l+=d,p=h.build(e,u);const f=e.getComponentType(u);f!==r&&(p=e.format(p,f,r)),a.push(p)}const c=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(c,s,t)}}const Eb=yr.join("");class Kd extends re{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(yr.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let n=null;if(i>1){let r=null;this.getVectorLength()>=i&&(r=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const l=s.build(e,r);this.components.length===i&&this.components===Eb.slice(0,this.components.length)?n=e.format(l,r,t):n=e.format(`${l}.${this.components}`,this.getNodeType(e),t)}else n=s.build(e,t);return n}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Ab extends nt{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,n=this.getNodeType(e),r=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(s.length,r),l=i.build(e,a),c=t.build(e,n),h=e.getTypeLength(n),u=[];for(let d=0;d<h;d++){const p=yr[d];p===s[0]?(u.push(l),d+=s.length-1):u.push(c+"."+p)}return`${e.getType(n)}( ${u.join(", ")} )`}}class Rb extends nt{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),n=s.build(e),r=e.getVarFromNode(this),a=e.getPropertyName(r);e.addLineFlowCode(a+" = "+n,this);const l=e.getTypeLength(i),c=[];let h=0;for(let u=0;u<l;u++){const d=yr[u];d===t[h]?(c.push("1.0 - "+(a+"."+d)),h++):c.push(a+"."+d)}return`${e.getType(i)}( ${c.join(", ")} )`}}class pu extends re{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return this.nodeType===null?el(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=el(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=V_(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?jm(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const Jd=/float|u?int/;class ci extends pu{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return Jd.test(s)&&Jd.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class Nb extends re{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let ur=null;const qn=new Map;function O(o,e){if(qn.has(o)){console.warn(`THREE.TSL: Redefinition of method chaining '${o}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${o} is not a function`);qn.set(o,e)}const tg=o=>o.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),ep=o=>tg(o).split("").sort().join(""),sg={setup(o,e){const t=e.shift();return o(fl(t),...e)},get(o,e,t){if(typeof e=="string"&&o[e]===void 0){if(o.isStackNode!==!0&&e==="assign")return(...s)=>(ur.assign(t,...s),t);if(qn.has(e)){const s=qn.get(e);return o.isStackNode?(...i)=>t.add(s(...i)):(...i)=>s(t,...i)}else{if(e==="self")return o;if(e.endsWith("Assign")&&qn.has(e.slice(0,e.length-6))){const s=qn.get(e.slice(0,e.length-6));return o.isStackNode?(...i)=>t.assign(i[0],s(...i)):(...i)=>t.assign(s(t,...i))}else{if(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0)return e=tg(e),k(new Kd(t,e));if(/^set[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=ep(e.slice(3).toLowerCase()),s=>k(new Ab(o,e,k(s)));if(/^flip[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=ep(e.slice(4).toLowerCase()),()=>k(new Rb(k(o),e));if(e==="width"||e==="height"||e==="depth")return e==="width"?e="x":e==="height"?e="y":e==="depth"&&(e="z"),k(new Kd(o,e));if(/^\d+$/.test(e)===!0)return k(new Mo(t,new ci(Number(e),"uint")));if(/^get$/.test(e)===!0)return s=>k(new Nb(t,s))}}}return Reflect.get(o,e,t)},set(o,e,t,s){return typeof e=="string"&&o[e]===void 0&&(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0||e==="width"||e==="height"||e==="depth"||/^\d+$/.test(e)===!0)?(s[e].assign(t),!0):Reflect.set(o,e,t,s)}},Xl=new WeakMap,tp=new WeakMap,Pb=function(o,e=null){const t=el(o);if(t==="node"){let s=Xl.get(o);return s===void 0&&(s=new Proxy(o,sg),Xl.set(o,s),Xl.set(s,s)),s}else{if(e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string")return k(Oh(o,e));if(t==="shader")return L(o)}return o},Fb=function(o,e=null){for(const t in o)o[t]=k(o[t],e);return o},Db=function(o,e=null){const t=o.length;for(let s=0;s<t;s++)o[s]=k(o[s],e);return o},Ob=function(o,e=null,t=null,s=null){const i=h=>k(s!==null?Object.assign(h,s):h);let n,r=e,a,l;function c(h){let u;return r?u=/[a-z]/i.test(r)?r+"()":r:u=o.type,a!==void 0&&h.length<a?(console.error(`THREE.TSL: "${u}" parameter length is less than minimum required.`),h.concat(new Array(a-h.length).fill(0))):l!==void 0&&h.length>l?(console.error(`THREE.TSL: "${u}" parameter length exceeds limit.`),h.slice(0,l)):h}return e===null?n=(...h)=>i(new o(...tr(c(h)))):t!==null?(t=k(t),n=(...h)=>i(new o(e,...tr(c(h)),t))):n=(...h)=>i(new o(e,...tr(c(h)))),n.setParameterLength=(...h)=>(h.length===1?a=l=h[0]:h.length===2&&([a,l]=h),n),n.setName=h=>(r=h,n),n},Bb=function(o,...e){return k(new o(...tr(e)))};class Ib extends re{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t),n=t.namespace&&t.namespace===e.namespace?e.getNamespace("once"):"once";if(i[n])return i[n];let r=null;if(t.layout){let a=tp.get(e.constructor);a===void 0&&(a=new WeakMap,tp.set(e.constructor,a));let l=a.get(t);l===void 0&&(l=k(e.buildFunctionNode(t)),a.set(t,l)),e.addInclude(l),r=k(l.call(s))}else{const a=t.jsFunc,l=s!==null||a.length>1?a(s||[],e):a(e);r=k(l)}return t.once&&(i[n]=r),r}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getOutputNamespace();return t[s]=t[s]||this.setupOutput(e),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),n=e.getNodeProperties(this),r=e.getOutputNamespace(),a=this.getOutputNode(e);if(i==="setup"){const l=e.getNamespace("initialized");n[l]!==!0&&(n[l]=!0,n[r]=this.getOutputNode(e),n[r].build(e)),s=n[r]}else i==="analyze"?a.build(e,t):i==="generate"&&(s=a.build(e,t)||"");return s}}class Lb extends re{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1,this.namespace=null}setLayout(e){return this.layout=e,this}call(e=null){return fl(e),k(new Ib(this,e))}setup(){return this.call()}}const Ub=[!1,!0],kb=[0,1,2,3],zb=[-1,-2],ig=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],fu=new Map;for(const o of Ub)fu.set(o,new ci(o));const mu=new Map;for(const o of kb)mu.set(o,new ci(o,"uint"));const gu=new Map([...mu].map(o=>new ci(o.value,"int")));for(const o of zb)gu.set(o,new ci(o,"int"));const dl=new Map([...gu].map(o=>new ci(o.value)));for(const o of ig)dl.set(o,new ci(o));for(const o of ig)dl.set(-o,new ci(-o));const pl={bool:fu,uint:mu,ints:gu,float:dl},sp=new Map([...fu,...dl]),Oh=(o,e)=>sp.has(o)?sp.get(o):o.isNode===!0?o:new ci(o,e),Vb=o=>{try{return o.getNodeType()}catch{return}},rt=function(o,e=null){return(...t)=>{if((t.length===0||!["bool","float","int","uint"].includes(o)&&t.every(i=>typeof i!="object"))&&(t=[jm(o,...t)]),t.length===1&&e!==null&&e.has(t[0]))return k(e.get(t[0]));if(t.length===1){const i=Oh(t[0],o);return Vb(i)===o?k(i):k(new eg(i,o))}const s=t.map(i=>Oh(i));return k(new Cb(s,o))}},ip=o=>typeof o=="object"&&o!==null?o.value:o,Gb=o=>o!=null?o.nodeType||o.convertTo||(typeof o=="string"?o:null):null;function Kr(o,e){return new Proxy(new Lb(o,e),sg)}const k=(o,e=null)=>Pb(o,e),fl=(o,e=null)=>new Fb(o,e),tr=(o,e=null)=>new Db(o,e),U=(...o)=>new Ob(...o),G=(...o)=>new Bb(...o);let Hb=0;const L=(o,e=null)=>{let t=null;e!==null&&(typeof e=="object"?t=e.return:(typeof e=="string"?t=e:console.error("THREE.TSL: Invalid layout type."),e=null));const s=new Kr(o,t),i=(...n)=>{let r;fl(n),n[0]&&(n[0].isNode||Object.getPrototypeOf(n[0])!==Object.prototype)?r=[...n]:r=n[0];const l=s.call(r);return t==="void"&&l.toStack(),l};if(i.shaderNode=s,i.id=s.id,i.getNodeType=(...n)=>s.getNodeType(...n),i.getCacheKey=(...n)=>s.getCacheKey(...n),i.setLayout=n=>(s.setLayout(n),i),i.once=(n=null)=>(s.once=!0,s.namespace=n,i),e!==null){if(typeof e.inputs!="object"){const n={name:"fn"+Hb++,type:t,inputs:[]};for(const r in e)r!=="return"&&n.inputs.push({name:r,type:e[r]});e=n}i.setLayout(e)}return i},tl=o=>{ur=o},ng=()=>ur,Ze=(...o)=>ur.If(...o);function rg(o){return ur&&ur.add(o),o}O("toStack",rg);const Wb=new rt("color"),B=new rt("float",pl.float),ke=new rt("int",pl.ints),$b=new rt("uint",pl.uint),yu=new rt("bool",pl.bool),H=new rt("vec2"),qs=new rt("ivec2"),jb=new rt("uvec2"),qb=new rt("bvec2"),I=new rt("vec3"),Yb=new rt("ivec3"),Xb=new rt("uvec3"),Zb=new rt("bvec3"),ne=new rt("vec4"),Qb=new rt("ivec4"),Kb=new rt("uvec4"),Jb=new rt("bvec4"),xu=new rt("mat2"),Ft=new rt("mat3"),sr=new rt("mat4");O("toColor",Wb);O("toFloat",B);O("toInt",ke);O("toUint",$b);O("toBool",yu);O("toVec2",H);O("toIVec2",qs);O("toUVec2",jb);O("toBVec2",qb);O("toVec3",I);O("toIVec3",Yb);O("toUVec3",Xb);O("toBVec3",Zb);O("toVec4",ne);O("toIVec4",Qb);O("toUVec4",Kb);O("toBVec4",Jb);O("toMat2",xu);O("toMat3",Ft);O("toMat4",sr);const eT=U(Mo).setParameterLength(2),tT=(o,e)=>k(new eg(k(o),e));O("element",eT);O("convert",tT);O("append",o=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),rg(o)));class sT extends nt{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return yr.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=e.getNodeProperties(this);i.sourceNode=s,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),n=this.needsSplitAssign(e),r=s.getNodeType(e),a=s.build(e),l=i.build(e,r),c=i.getNodeType(e),h=e.getDataFromNode(this);let u;if(h.initialized===!0)t!=="void"&&(u=a);else if(n){const d=e.getVarFromNode(this,null,r),p=e.getPropertyName(d);e.addLineFlowCode(`${p} = ${l}`,this);const f=s.node,y=f.node.context({assign:!0}).build(e);for(let g=0;g<f.components.length;g++){const _=f.components[g];e.addLineFlowCode(`${y}.${_} = ${p}[ ${g} ]`,this)}t!=="void"&&(u=a)}else u=`${a} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(u,this),t!=="void"&&(u=a));return h.initialized=!0,e.format(u,r,t)}}const iT=U(sT).setParameterLength(2);O("assign",iT);class np extends nt{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getNodeType(e){return this.nodeType===null&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const nT=(...o)=>{let e;if(o.length===1){const t=o[0];e=new np(null,t.length,t)}else{const t=o[0],s=o[1];e=new np(t,s)}return k(e)};O("toArray",(o,e)=>nT(Array(e).fill(o)));class og extends re{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const rT=o=>new og(o),_u=(o,e=0)=>new og(o,!0,e),oT=_u("frame"),Q=_u("render"),ag=rT("object");class Co extends pu{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=ag}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate(i=>{const n=e(i,s);n!==void 0&&(this.value=n)},t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let n=e.getNodeFromHash(i);n===void 0&&(e.setHashNode(this,i),n=this);const r=n.getInputType(e),a=e.getUniformFromNode(n,r,e.shaderStage,this.name||e.context.label),l=e.getPropertyName(a);return e.context.label!==void 0&&delete e.context.label,e.format(l,s,t)}}const K=(o,e)=>{const t=Gb(e||o),s=o&&o.isNode===!0?o.node&&o.node.value||o.value:o;return k(new Co(s,t))};class Re extends re{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return this.varying===!0?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const lg=(o,e)=>k(new Re(o,e)),sl=(o,e)=>k(new Re(o,e,!0)),Se=G(Re,"vec4","DiffuseColor"),rp=G(Re,"vec3","EmissiveColor"),Xs=G(Re,"float","Roughness"),il=G(Re,"float","Metalness"),Bh=G(Re,"float","Clearcoat"),nl=G(Re,"float","ClearcoatRoughness"),Yn=G(Re,"vec3","Sheen"),bu=G(Re,"float","SheenRoughness"),Tu=G(Re,"float","Iridescence"),cg=G(Re,"float","IridescenceIOR"),hg=G(Re,"float","IridescenceThickness"),Ih=G(Re,"float","AlphaT"),tn=G(Re,"float","Anisotropy"),Fa=G(Re,"vec3","AnisotropyT"),ir=G(Re,"vec3","AnisotropyB"),Yt=G(Re,"color","SpecularColor"),rl=G(Re,"float","SpecularF90"),Lh=G(Re,"float","Shininess"),co=G(Re,"vec4","Output"),Zl=G(Re,"float","dashSize"),op=G(Re,"float","gapSize"),Da=G(Re,"float","IOR"),Uh=G(Re,"float","Transmission"),ug=G(Re,"float","Thickness"),dg=G(Re,"float","AttenuationDistance"),pg=G(Re,"color","AttenuationColor"),fg=G(Re,"float","Dispersion");class aT extends nt{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),n=this.parameters,r=(l,c)=>{const h=c.type,u=h==="pointer";let d;return u?d="&"+l.build(e):d=l.build(e,h),d};if(Array.isArray(n)){if(n.length>i.length)console.error("THREE.TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),n.length=i.length;else if(n.length<i.length)for(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<i.length;)n.push(B(0));for(let l=0;l<n.length;l++)t.push(r(n[l],i[l]))}else for(const l of i){const c=n[l.name];c!==void 0?t.push(r(c,l)):(console.error(`THREE.TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(r(B(0),l)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const lT=(o,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?tr(e):fl(e[0]),k(new aT(k(o),e)));O("call",lT);const cT={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class We extends nt{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let n=new We(e,t,s);for(let r=0;r<i.length-1;r++)n=new We(e,n,i[r]);t=n,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(cT[this.op],t)}getNodeType(e){const t=this.op,s=this.aNode,i=this.bNode,n=s.getNodeType(e),r=i?i.getNodeType(e):null;if(n==="void"||r==="void")return"void";if(t==="%")return n;if(t==="~"||t==="&"||t==="|"||t==="^"||t===">>"||t==="<<")return e.getIntegerType(n);if(t==="!"||t==="&&"||t==="||"||t==="^^")return"bool";if(t==="=="||t==="!="||t==="<"||t===">"||t==="<="||t===">="){const a=Math.max(e.getTypeLength(n),e.getTypeLength(r));return a>1?`bvec${a}`:"bool"}else{if(e.isMatrix(n)){if(r==="float")return n;if(e.isVector(r))return e.getVectorFromMatrix(n);if(e.isMatrix(r))return n}else if(e.isMatrix(r)){if(n==="float")return r;if(e.isVector(n))return e.getVectorFromMatrix(r)}return e.getTypeLength(r)>e.getTypeLength(n)?r:n}}generate(e,t){const s=this.op,{aNode:i,bNode:n}=this,r=this.getNodeType(e);let a=null,l=null;r!=="void"?(a=i.getNodeType(e),l=n?n.getNodeType(e):null,s==="<"||s===">"||s==="<="||s===">="||s==="=="||s==="!="?e.isVector(a)?l=a:e.isVector(l)?a=l:a!==l&&(a=l="float"):s===">>"||s==="<<"?(a=r,l=e.changeComponentType(l,"uint")):s==="%"?(a=r,l=e.isInteger(a)&&e.isInteger(l)?l:a):e.isMatrix(a)?l==="float"?l="float":e.isVector(l)?l=e.getVectorFromMatrix(a):e.isMatrix(l)||(a=l=r):e.isMatrix(l)?a==="float"?a="float":e.isVector(a)?a=e.getVectorFromMatrix(l):a=l=r:a=l=r):a=l=r;const c=i.build(e,a),h=n?n.build(e,l):null,u=e.getFunctionOperator(s);if(t!=="void"){const d=e.renderer.coordinateSystem===Ut;if(s==="=="||s==="!="||s==="<"||s===">"||s==="<="||s===">=")return d?e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t);if(s==="%")return e.isInteger(l)?e.format(`( ${c} % ${h} )`,r,t):e.format(`${this.getOperatorMethod(e,r)}( ${c}, ${h} )`,r,t);if(s==="!"||s==="~")return e.format(`(${s}${c})`,a,t);if(u)return e.format(`${u}( ${c}, ${h} )`,r,t);if(e.isMatrix(a)&&l==="float")return e.format(`( ${h} ${s} ${c} )`,r,t);if(a==="float"&&e.isMatrix(l))return e.format(`${c} ${s} ${h}`,r,t);{let p=`( ${c} ${s} ${h} )`;return!d&&r==="bool"&&e.isVector(a)&&e.isVector(l)&&(p=`all${p}`),e.format(p,r,t)}}else if(a!=="void")return u?e.format(`${u}( ${c}, ${h} )`,r,t):e.isMatrix(a)&&l==="float"?e.format(`${h} ${s} ${c}`,r,t):e.format(`${c} ${s} ${h}`,r,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Dt=U(We,"+").setParameterLength(2,1/0).setName("add"),At=U(We,"-").setParameterLength(2,1/0).setName("sub"),fe=U(We,"*").setParameterLength(2,1/0).setName("mul"),Us=U(We,"/").setParameterLength(2,1/0).setName("div"),ml=U(We,"%").setParameterLength(2).setName("mod"),mg=U(We,"==").setParameterLength(2).setName("equal"),hT=U(We,"!=").setParameterLength(2).setName("notEqual"),uT=U(We,"<").setParameterLength(2).setName("lessThan"),dT=U(We,">").setParameterLength(2).setName("greaterThan"),pT=U(We,"<=").setParameterLength(2).setName("lessThanEqual"),fT=U(We,">=").setParameterLength(2).setName("greaterThanEqual"),mT=U(We,"&&").setParameterLength(2,1/0).setName("and"),gT=U(We,"||").setParameterLength(2,1/0).setName("or"),yT=U(We,"!").setParameterLength(1).setName("not"),xT=U(We,"^^").setParameterLength(2).setName("xor"),_T=U(We,"&").setParameterLength(2).setName("bitAnd"),bT=U(We,"~").setParameterLength(2).setName("bitNot"),TT=U(We,"|").setParameterLength(2).setName("bitOr"),ST=U(We,"^").setParameterLength(2).setName("bitXor"),vT=U(We,"<<").setParameterLength(2).setName("shiftLeft"),wT=U(We,">>").setParameterLength(2).setName("shiftRight"),MT=L(([o])=>(o.addAssign(1),o)),CT=L(([o])=>(o.subAssign(1),o)),ET=L(([o])=>{const e=ke(o).toConst();return o.addAssign(1),e}),AT=L(([o])=>{const e=ke(o).toConst();return o.subAssign(1),e});O("add",Dt);O("sub",At);O("mul",fe);O("div",Us);O("mod",ml);O("equal",mg);O("notEqual",hT);O("lessThan",uT);O("greaterThan",dT);O("lessThanEqual",pT);O("greaterThanEqual",fT);O("and",mT);O("or",gT);O("not",yT);O("xor",xT);O("bitAnd",_T);O("bitNot",bT);O("bitOr",TT);O("bitXor",ST);O("shiftLeft",vT);O("shiftRight",wT);O("incrementBefore",MT);O("decrementBefore",CT);O("increment",ET);O("decrement",AT);const RT=(o,e)=>(console.warn('THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.'),ml(o,e)),NT=(o,e)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),ml(ke(o),ke(e)));O("remainder",RT);O("modInt",NT);class A extends nt{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===A.MAX||e===A.MIN)&&arguments.length>3){let n=new A(e,t,s);for(let r=2;r<arguments.length-1;r++)n=new A(e,n,arguments[r]);t=n,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,n=e.isMatrix(t)?0:e.getTypeLength(t),r=e.isMatrix(s)?0:e.getTypeLength(s),a=e.isMatrix(i)?0:e.getTypeLength(i);return n>r&&n>a?t:r>a?s:a>n?i:t}getNodeType(e){const t=this.method;return t===A.LENGTH||t===A.DISTANCE||t===A.DOT?"float":t===A.CROSS?"vec3":t===A.ALL||t===A.ANY?"bool":t===A.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let n=null;if(i===A.ONE_MINUS)n=At(1,t);else if(i===A.RECIPROCAL)n=Us(1,t);else if(i===A.DIFFERENCE)n=ns(At(t,s));else if(i===A.TRANSFORM_DIRECTION){let r=t,a=s;e.isMatrix(r.getNodeType(e))?a=ne(I(a),0):r=ne(I(r),0);const l=fe(r,a).xyz;n=To(l)}return n!==null?n:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const n=this.getNodeType(e),r=this.getInputType(e),a=this.aNode,l=this.bNode,c=this.cNode,h=e.renderer.coordinateSystem;if(i===A.NEGATE)return e.format("( - "+a.build(e,r)+" )",n,t);{const u=[];return i===A.CROSS?u.push(a.build(e,n),l.build(e,n)):h===Ut&&i===A.STEP?u.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":r),l.build(e,r)):h===Ut&&(i===A.MIN||i===A.MAX)?u.push(a.build(e,r),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":r)):i===A.REFRACT?u.push(a.build(e,r),l.build(e,r),c.build(e,"float")):i===A.MIX?u.push(a.build(e,r),l.build(e,r),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":r)):(h===Oi&&i===A.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===A.DFDX||i===A.DFDY)&&(console.warn(`THREE.TSL: '${i}' is not supported in the ${e.shaderStage} stage.`),i="/*"+i+"*/"),u.push(a.build(e,r)),l!==null&&u.push(l.build(e,r)),c!==null&&u.push(c.build(e,r))),e.format(`${e.getMethod(i,n)}( ${u.join(", ")} )`,n,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}A.ALL="all";A.ANY="any";A.RADIANS="radians";A.DEGREES="degrees";A.EXP="exp";A.EXP2="exp2";A.LOG="log";A.LOG2="log2";A.SQRT="sqrt";A.INVERSE_SQRT="inversesqrt";A.FLOOR="floor";A.CEIL="ceil";A.NORMALIZE="normalize";A.FRACT="fract";A.SIN="sin";A.COS="cos";A.TAN="tan";A.ASIN="asin";A.ACOS="acos";A.ATAN="atan";A.ABS="abs";A.SIGN="sign";A.LENGTH="length";A.NEGATE="negate";A.ONE_MINUS="oneMinus";A.DFDX="dFdx";A.DFDY="dFdy";A.ROUND="round";A.RECIPROCAL="reciprocal";A.TRUNC="trunc";A.FWIDTH="fwidth";A.TRANSPOSE="transpose";A.BITCAST="bitcast";A.EQUALS="equals";A.MIN="min";A.MAX="max";A.STEP="step";A.REFLECT="reflect";A.DISTANCE="distance";A.DIFFERENCE="difference";A.DOT="dot";A.CROSS="cross";A.POW="pow";A.TRANSFORM_DIRECTION="transformDirection";A.MIX="mix";A.CLAMP="clamp";A.REFRACT="refract";A.SMOOTHSTEP="smoothstep";A.FACEFORWARD="faceforward";const PT=B(1e-6),FT=B(Math.PI),DT=U(A,A.ALL).setParameterLength(1),OT=U(A,A.ANY).setParameterLength(1),BT=U(A,A.RADIANS).setParameterLength(1),IT=U(A,A.DEGREES).setParameterLength(1),gg=U(A,A.EXP).setParameterLength(1),bo=U(A,A.EXP2).setParameterLength(1),yg=U(A,A.LOG).setParameterLength(1),ii=U(A,A.LOG2).setParameterLength(1),Su=U(A,A.SQRT).setParameterLength(1),LT=U(A,A.INVERSE_SQRT).setParameterLength(1),un=U(A,A.FLOOR).setParameterLength(1),vu=U(A,A.CEIL).setParameterLength(1),To=U(A,A.NORMALIZE).setParameterLength(1),Ui=U(A,A.FRACT).setParameterLength(1),_s=U(A,A.SIN).setParameterLength(1),wi=U(A,A.COS).setParameterLength(1),UT=U(A,A.TAN).setParameterLength(1),kT=U(A,A.ASIN).setParameterLength(1),xg=U(A,A.ACOS).setParameterLength(1),_g=U(A,A.ATAN).setParameterLength(1,2),ns=U(A,A.ABS).setParameterLength(1),ol=U(A,A.SIGN).setParameterLength(1),ni=U(A,A.LENGTH).setParameterLength(1),zT=U(A,A.NEGATE).setParameterLength(1),VT=U(A,A.ONE_MINUS).setParameterLength(1),bg=U(A,A.DFDX).setParameterLength(1),Tg=U(A,A.DFDY).setParameterLength(1),GT=U(A,A.ROUND).setParameterLength(1),HT=U(A,A.RECIPROCAL).setParameterLength(1),WT=U(A,A.TRUNC).setParameterLength(1),$T=U(A,A.FWIDTH).setParameterLength(1),jT=U(A,A.TRANSPOSE).setParameterLength(1),qT=(o,e)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),mg(o,e)),dr=U(A,A.MIN).setParameterLength(2,1/0),vt=U(A,A.MAX).setParameterLength(2,1/0),Sg=U(A,A.STEP).setParameterLength(2),YT=U(A,A.REFLECT).setParameterLength(2),XT=U(A,A.DISTANCE).setParameterLength(2),ZT=U(A,A.DIFFERENCE).setParameterLength(2),wu=U(A,A.DOT).setParameterLength(2),vg=U(A,A.CROSS).setParameterLength(2),gl=U(A,A.POW).setParameterLength(2),wg=U(A,A.POW,2).setParameterLength(1),QT=U(A,A.POW,3).setParameterLength(1),KT=U(A,A.POW,4).setParameterLength(1),JT=U(A,A.TRANSFORM_DIRECTION).setParameterLength(2),eS=o=>fe(ol(o),gl(ns(o),1/3)),Mg=o=>wu(o,o),Ve=U(A,A.MIX).setParameterLength(3),ai=(o,e=0,t=1)=>k(new A(A.CLAMP,k(o),k(e),k(t))),Cg=o=>ai(o),Eg=U(A,A.REFRACT).setParameterLength(3),Bi=U(A,A.SMOOTHSTEP).setParameterLength(3),tS=U(A,A.FACEFORWARD).setParameterLength(3),sS=L(([o])=>{const s=43758.5453,i=wu(o.xy,H(12.9898,78.233)),n=ml(i,FT);return Ui(_s(n).mul(s))}),iS=(o,e,t)=>Ve(e,t,o),nS=(o,e,t)=>Bi(e,t,o),rS=(o,e)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),_g(o,e));O("all",DT);O("any",OT);O("equals",qT);O("radians",BT);O("degrees",IT);O("exp",gg);O("exp2",bo);O("log",yg);O("log2",ii);O("sqrt",Su);O("inverseSqrt",LT);O("floor",un);O("ceil",vu);O("normalize",To);O("fract",Ui);O("sin",_s);O("cos",wi);O("tan",UT);O("asin",kT);O("acos",xg);O("atan",_g);O("abs",ns);O("sign",ol);O("length",ni);O("lengthSq",Mg);O("negate",zT);O("oneMinus",VT);O("dFdx",bg);O("dFdy",Tg);O("round",GT);O("reciprocal",HT);O("trunc",WT);O("fwidth",$T);O("atan2",rS);O("min",dr);O("max",vt);O("step",Sg);O("reflect",YT);O("distance",XT);O("dot",wu);O("cross",vg);O("pow",gl);O("pow2",wg);O("pow3",QT);O("pow4",KT);O("transformDirection",JT);O("mix",iS);O("clamp",ai);O("refract",Eg);O("smoothstep",nS);O("faceForward",tS);O("difference",ZT);O("saturate",Cg);O("cbrt",eS);O("transpose",jT);O("rand",sS);class oS extends re{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(t===void 0)return this.setup(e),this.getNodeType(e);const i=t.getNodeType(e);if(s!==null){const n=s.getNodeType(e);if(e.getTypeLength(n)>e.getTypeLength(i))return n}return i}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,n=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=n,i!==null&&(e.getDataFromNode(i).parentNodeBlock=n);const r=e.getNodeProperties(this);r.condNode=t,r.ifNode=s.context({nodeBlock:s}),r.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;const{condNode:n,ifNode:r,elseNode:a}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",h=c?lg(s).build(e):"";i.nodeProperty=h;const u=n.build(e,"bool");e.addFlowCode(`
|
|
49
|
+
C11,8.22,10.74,8,10.43,8z`})});function fm(o){return E.jsx("li",{className:`reorder-item ${o.draggingIndex===o.index?"dragging":""}`,draggable:!0,onDragStart:()=>o.onDragStart(o.index),onDragOver:e=>{e.preventDefault(),o.onDragOver(o.index)},onDragEnd:o.onDragEnd,children:E.jsxs("div",{children:[Gx,E.jsx("span",{children:o.title}),E.jsx("button",{className:"closeIcon",onClick:()=>o.onDelete(o.index),children:zx})]})})}function mm(o){const[e,t]=W.useState(!1),[s,i]=W.useState(o.options),[n,r]=W.useState(null),a=p=>{o.onDragComplete(p),i(p)},l=p=>{const f=[...s];f.splice(p,1),a(f)},c=p=>{r(p)},h=p=>{if(n===p||n===null)return;const f=[...s],m=f.splice(n,1)[0];f.splice(p,0,m),r(p),i(f)},u=()=>{o.onDragComplete(s),r(null)};let d="dropdown draggable";return o.subdropdown&&(d+=" subdropdown"),E.jsxs("div",{className:d,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[E.jsx(Qh,{title:o.title}),E.jsx("ul",{className:"reorder-list",style:{display:e?"block":"none"},children:s.map((p,f)=>E.jsx(fm,{title:p,index:f,draggingIndex:n,onDelete:l,onDragStart:c,onDragOver:h,onDragEnd:u},p))})]})}function gm(o){const[e,t]=W.useState(!1),s=[];o.options.map((n,r)=>{o.onSelect!==void 0&&(n.onSelect=o.onSelect),s.push(E.jsx(ym,{option:n},r))});let i="dropdown";return o.subdropdown&&(i+=" subdropdown"),E.jsxs("div",{className:i,onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[E.jsx(Qh,{title:o.title}),E.jsx("ul",{style:{visibility:e?"visible":"hidden"},children:s})]})}function ym(o){const{option:e}=o,[t,s]=W.useState("");let i;switch(e.type){case"draggable":i=E.jsx(mm,{title:e.title,options:e.value,onDragComplete:n=>{e.onDragComplete!==void 0&&e.onDragComplete(n)},subdropdown:!0});break;case"dropdown":i=E.jsx(gm,{title:e.title,options:e.value,onSelect:e.onSelect,subdropdown:!0});break;case"option":i=E.jsx("button",{onClick:()=>{e.onSelect!==void 0&&e.onSelect(e.value),e.selectable&&(t!==e.title?s(e.title):s(""))},children:e.title});break}return E.jsx("li",{className:t===e.title?"selected":"",children:i},ht())}function Qn(o){const[e,t]=W.useState(o.open!==void 0?o.open:!1),[s,i]=W.useState(o.visible!==void 0?o.visible:!1),n=!e||o.children===void 0,r=()=>{o.three.dispatchEvent({type:ce.REMOVE_SCENE,value:o.scene})};return E.jsxs("div",{className:`accordion ${n?"hide":""}`,children:[E.jsxs("button",{className:"toggle",onClick:()=>{const a=!e;o.onToggle!==void 0&&o.onToggle(a),t(a)},children:[E.jsx("p",{className:`status ${e?"open":""}`,children:"Toggle"}),E.jsx("p",{className:"label",children:yo(o.label)})]}),o.onRefresh?E.jsxs(E.Fragment,{children:[E.jsx("button",{className:"visibility",style:{opacity:s?1:.25},onClick:()=>{const l=o.three.getScene(o.scene.uuid);if(l){const c=!l.visible;l.visible=c,i(c)}}}),E.jsx("button",{className:"refresh",onClick:o.onRefresh}),E.jsx("button",{className:"remove",onClick:r})]}):null,o.button,E.jsx("div",{className:e?"open":"",children:E.jsx("div",{children:o.children})},Math.random())]})}function Jh(o){if(o.child===void 0)return console.log("Hermes - No child attached"),null;const e=W.useRef(null),[t,s]=W.useState(!1),i=o.child.children.length>0,n=[];return o.child.children.length>0&&o.child.children.map((r,a)=>{n.push(E.jsx(Jh,{child:r,three:o.three},a))}),W.useEffect(()=>{if(o.child){const r=o.child.uuid.split(".")[0],a=o.three.getScene(r);if(a!==null)try{const l=a.getObjectByProperty("uuid",o.child.uuid);l!==void 0?e.current.style.opacity=l.visible?"1":"0.25":console.log(`Hermes - Can't find child: ${o.child.uuid}`)}catch(l){console.log("Error looking for child:",l),console.log(o.child),console.log(o.three.scenes),console.log(a)}else console.log(`Hermes (ChildObject) - Can't find Scene: ${r} with child UUID: ${o.child.uuid}`,o.three.scenes,o.three.scene,a)}},[t]),E.jsxs("div",{className:"childObject",children:[E.jsxs("div",{className:"child",children:[i?E.jsx("button",{className:"status",style:{backgroundPositionX:t?"-14px":"2px"},onClick:()=>{s(!t)}}):null,E.jsx("button",{className:"name",style:{left:i?"20px":"5px"},onClick:()=>{o.child!==void 0?(o.three.getObject(o.child.uuid),!t&&i&&s(!0)):console.log("Hermes - No child attached...")},children:o.child.name.length>0?`${o.child.name} (${o.child.type})`:`${o.child.type}::${o.child.uuid}`}),E.jsx("button",{className:"visibility",ref:e,onClick:()=>{if(o.child){const r=o.three.getScene(o.child.uuid);if(r!==null){const a=r.getObjectByProperty("uuid",o.child.uuid);if(a!==void 0){const l="visible",c=!a.visible;e.current.style.opacity=c?"1":"0.25",o.three.updateObject(o.child.uuid,l,c),Ye(a,l,c)}else console.log(`Hermes - Couldn't find object: ${o.child.uuid}`,r)}else console.log(`Hermes - Couldn't find object in scene: ${o.child.uuid}, ${o.child.name}`)}}}),E.jsx("div",{className:`icon ${Px(o.child)}`})]}),E.jsx("div",{className:t?"open":"",children:E.jsx("div",{className:"container",children:n})})]},Math.random())}function Aa(o){const e=[];return o.child?.children.map((t,s)=>{e.push(E.jsx(Jh,{child:t,scene:o.scene,three:o.three},s))}),E.jsx("div",{className:`scene ${o.class!==void 0?o.class:""}`,children:e})}function Qr(o){const[e,t]=W.useState(o.defaultValue);return W.useEffect(()=>{let s=!1,i=-1,n=0,r=o.defaultValue,a=!1;const l=p=>{a=p.ctrlKey},c=p=>{s=!0,n=Number(o.input.current?.value),i=p.clientX,document.addEventListener("mouseup",u,!1),document.addEventListener("mousemove",h,!1),document.addEventListener("contextmenu",u,!1)},h=p=>{if(!s)return;const f=o.step!==void 0?o.step:1,m=(p.clientX-i)*f*(a?10:1);r=Number((n+m).toFixed(4)),o.min!==void 0&&(r=Math.max(r,o.min)),o.max!==void 0&&(r=Math.min(r,o.max)),o.onChange!==void 0&&o.onChange(r),t(r)},u=()=>{s=!1,document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u)},d=p=>{const f=Number(p.target.value);o.onChange!==void 0&&o.onChange(f),t(f)};return o.label.current?.addEventListener("mousedown",c,!1),o.sliderRef!==void 0&&o.sliderRef.current?.addEventListener("input",d),document.addEventListener("keydown",l,!1),document.addEventListener("keyup",l,!1),()=>{o.label.current?.removeEventListener("mousedown",c),o.sliderRef!==void 0&&o.sliderRef.current?.removeEventListener("input",d),document.removeEventListener("mouseup",u),document.removeEventListener("mousemove",h),document.removeEventListener("contextmenu",u),document.removeEventListener("keydown",l),document.addEventListener("keyup",l,!1)}},[]),e}function hn(o){const e=W.useRef(null),t=W.useRef(null),[s,i]=W.useState(o.value);return Qr({label:o.labelRef,input:e,sliderRef:t,defaultValue:s,min:o.min,max:o.max,step:o.step,onChange:n=>{i(n),o.onChange!==void 0&&o.onChange(o.prop,n)}}),E.jsxs(E.Fragment,{children:[o.type==="number"&&E.jsx("input",{alt:o.alt,className:o.className,ref:e,type:"number",value:s,min:o.min,max:o.max,step:o.step,disabled:o.disabled,name:ht(),onChange:n=>{if(i(n.target.value),n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||o.onChange!==void 0&&o.onChange(o.prop,r)}}),o.type==="range"&&E.jsxs(E.Fragment,{children:[E.jsx("input",{type:"text",value:s.toString(),disabled:o.disabled,ref:e,className:"min",name:ht(),onChange:n=>{if(n.target.value.length===0)return;const r=Number(n.target.value);isNaN(r)||(i(r),o.onChange!==void 0&&o.onChange(o.prop,r))}}),E.jsx("input",{disabled:o.disabled,type:"range",value:s,min:o.min,max:o.max,step:o.step,ref:t,name:ht(),onChange:go})]})]})}function Vx(o){const e=W.useRef(null),t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),a=W.useRef(null),l=W.useRef(null),c=W.useRef(null),h=W.useRef(null),[u,d]=W.useState(o.value.x),[p,f]=W.useState(o.value.y),[m,x]=W.useState({min:Math.min(o.min,Math.min(o.value.x,o.value.y)),max:Math.max(o.max,Math.max(o.value.x,o.value.y))}),[g,_]=W.useState(!1);Qr({label:a,input:e,defaultValue:u,min:m.min,max:m.max,step:.01,onChange:P=>{d(P),o.onChange({target:{value:{x:P,y:p}}})}}),Qr({label:l,input:t,defaultValue:p,min:m.min,max:m.max,step:.01,onChange:P=>{f(P),o.onChange({target:{value:{x:u,y:P}}})}}),Qr({label:c,input:s,defaultValue:m.min,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{x({min:P,max:m.max})}}),Qr({label:h,input:i,defaultValue:m.max,min:m.min-1,max:m.max+1,step:.01,onChange:P=>{x({min:m.min,max:P})}});function b(){g||(window.addEventListener("mousemove",S),window.addEventListener("mouseup",T),_(!0))}function T(){window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",T),_(!1)}function S(P){const z=n.current.getBoundingClientRect(),$=Si(0,99,P.clientX-z.left)/99,q=1-Si(0,99,P.clientY-z.top)/99,j=is(lr(m.min,m.max,$),3),X=is(lr(m.min,m.max,q),3);o.onChange({target:{value:{x:j,y:X}}}),d(j),f(X)}function C(){const P=Number(s.current.value);x({min:P,max:m.max}),u<P&&d(Si(P,m.max,u)),p<P&&f(Si(P,m.max,p))}function w(){const P=Number(i.current.value);x({min:m.min,max:P}),u>P&&d(Si(m.min,P,u)),p>P&&f(Si(m.min,P,p))}W.useEffect(()=>{r.current.style.left=`${Va(m.min,m.max,u)*100}%`,r.current.style.top=`${(1-Va(m.min,m.max,p))*100}%`},[m,u,p]);const R=o.step!==void 0?o.step:.01;return E.jsxs("div",{className:"vector2",children:[E.jsxs("div",{className:"fields",children:[E.jsxs("div",{children:[E.jsx("span",{ref:a,children:"X"}),E.jsx("input",{ref:e,type:"number",value:u,min:m.min,max:m.max,step:R,name:ht(),onChange:P=>{if(d(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(o.onChange({target:{value:{x:z,y:p}}}),z<m.min&&x({min:z,max:m.max}))}})]}),E.jsxs("div",{children:[E.jsx("span",{ref:l,children:"Y"}),E.jsx("input",{ref:t,type:"number",value:p,min:m.min,max:m.max,step:R,name:ht(),onChange:P=>{if(f(P.target.value),P.target.value.length===0)return;const z=Number(P.target.value);isNaN(z)||(o.onChange({target:{value:{x:u,y:z}}}),z>m.max&&x({min:m.min,max:z}))}})]}),E.jsxs("div",{children:[E.jsx("span",{ref:c,children:"Min"}),E.jsx("input",{ref:s,type:"number",value:m.min,step:R,name:ht(),onChange:C})]}),E.jsxs("div",{children:[E.jsx("span",{ref:h,children:"Max"}),E.jsx("input",{ref:i,type:"number",value:m.max,step:R,name:ht(),onChange:w})]})]}),E.jsxs("div",{className:"input",ref:n,onMouseDown:b,onMouseUp:T,children:[E.jsx("div",{className:"x"}),E.jsx("div",{className:"y"}),E.jsx("div",{className:"pt",ref:r})]})]})}const yt=["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"];let Md=1234567;const ao=Math.PI/180,cr=180/Math.PI;function Ks(){const o=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return(yt[o&255]+yt[o>>8&255]+yt[o>>16&255]+yt[o>>24&255]+"-"+yt[e&255]+yt[e>>8&255]+"-"+yt[e>>16&15|64]+yt[e>>24&255]+"-"+yt[t&63|128]+yt[t>>8&255]+"-"+yt[t>>16&255]+yt[t>>24&255]+yt[s&255]+yt[s>>8&255]+yt[s>>16&255]+yt[s>>24&255]).toLowerCase()}function pe(o,e,t){return Math.max(e,Math.min(t,o))}function eu(o,e){return(o%e+e)%e}function Ji(o,e,t,s,i){return s+(o-e)*(i-s)/(t-e)}function Hx(o,e,t){return o!==e?(t-o)/(e-o):0}function Pi(o,e,t){return(1-t)*o+t*e}function Wx(o,e,t,s){return Pi(o,e,1-Math.exp(-t*s))}function $x(o,e=1){return e-Math.abs(eu(o,e*2)-e)}function jx(o,e,t){return o<=e?0:o>=t?1:(o=(o-e)/(t-e),o*o*(3-2*o))}function qx(o,e,t){return o<=e?0:o>=t?1:(o=(o-e)/(t-e),o*o*o*(o*(o*6-15)+10))}function Yx(o,e){return o+Math.floor(Math.random()*(e-o+1))}function Xx(o,e){return o+Math.random()*(e-o)}function Zx(o){return o*(.5-Math.random())}function Kx(o){o!==void 0&&(Md=o);let e=Md+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Wa(o){return o*ao}function xm(o){return o*cr}function Qx(o){return(o&o-1)===0&&o!==0}function Jx(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function e_(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function t_(o,e,t,s,i){const n=Math.cos,r=Math.sin,a=n(t/2),l=r(t/2),c=n((e+s)/2),h=r((e+s)/2),u=n((e-s)/2),d=r((e-s)/2),p=n((s-e)/2),f=r((s-e)/2);switch(i){case"XYX":o.set(a*h,l*u,l*d,a*c);break;case"YZY":o.set(l*d,a*h,l*u,a*c);break;case"ZXZ":o.set(l*u,l*d,a*h,a*c);break;case"XZX":o.set(a*h,l*f,l*p,a*c);break;case"YXY":o.set(l*p,a*h,l*f,a*c);break;case"ZYZ":o.set(l*f,l*p,a*h,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Rt(o,e){switch(e.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("Invalid component type.")}}function ae(o,e){switch(e.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("Invalid component type.")}}const s_={DEG2RAD:ao,RAD2DEG:cr,generateUUID:Ks,clamp:pe,euclideanModulo:eu,mapLinear:Ji,inverseLerp:Hx,lerp:Pi,damp:Wx,pingpong:$x,smoothstep:jx,smootherstep:qx,randInt:Yx,randFloat:Xx,randFloatSpread:Zx,seededRandom:Kx,degToRad:Wa,radToDeg:xm,isPowerOfTwo:Qx,ceilPowerOfTwo:Jx,floorPowerOfTwo:e_,setQuaternionFromProperEuler:t_,normalize:ae,denormalize:Rt};function Cd(o){const e=o.value.x!==void 0&&o.value.y!==void 0&&o.value.z!==void 0,t=o.value.isEuler!==void 0,s=o.value.elements!==void 0,i=o.step!==void 0?o.step:.01,n=[];if(t){const r=W.useMemo(()=>o.value,[]);["_x","_y","_z"].forEach(l=>{const c=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("span",{ref:c,children:l.substring(1).toUpperCase()}),E.jsx(hn,{value:xm(r[l]),type:"number",prop:l,step:.1,labelRef:c,onChange:(h,u)=>{r[h]=Wa(u),o.onChange({target:{value:r}})}})]},l))})}else if(e){const r=W.useMemo(()=>o.value,[]),a=(c,h)=>{r[c]=h,o.onChange({target:{value:r}})};["x","y","z"].forEach(c=>{const h=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("label",{ref:h,children:c.toUpperCase()}),E.jsx(hn,{value:r[c],type:"number",prop:c,step:i,labelRef:h,onChange:a})]},c))})}else if(s){const r=W.useMemo(()=>o.value,[]),a=(l,c)=>{const h=Number(l);r.elements[h]=c,o.onChange({target:{value:r}})};for(let l=0;l<9;l++){const c=W.useRef(null);n.push(E.jsxs("div",{children:[E.jsx("label",{ref:c,children:l+1}),E.jsx(hn,{value:r.elements[l],type:"number",prop:l.toString(),step:i,labelRef:c,onChange:a})]},l.toString()))}}return E.jsx("div",{className:"grid3",children:n},Math.random().toString())}function i_(o){const e=o.value.x!==void 0,t=o.step!==void 0?o.step:.01,s=[];if(e){const i=W.useMemo(()=>o.value,[]),n=(a,l)=>{i[a]=l,o.onChange({target:{value:i}})};["x","y","z","w"].forEach(a=>{const l=W.useRef(null);s.push(E.jsxs("div",{children:[E.jsx("label",{ref:l,children:a.toUpperCase()}),E.jsx(hn,{value:i[a],type:"number",prop:a,step:t,labelRef:l,onChange:n})]},a))})}else{const i=W.useMemo(()=>o.value,[]),n=(r,a)=>{const l=Number(r);i.elements[l]=a,o.onChange({target:{value:i}})};for(let r=0;r<16;r++){const a=W.useRef(null);s.push(E.jsxs("div",{children:[E.jsx("span",{ref:a,children:r+1}),E.jsx(hn,{value:i.elements[r],type:"number",prop:r.toString(),step:t,labelRef:a,onChange:n})]},r.toString()))}}return E.jsx("div",{className:"grid4",children:s})}function n_(o){return!(o==="defaultAttributeValues"||o==="forceSinglePass"||o==="linecap"||o==="linejoin"||o==="linewidth"||o==="normalMapType"||o==="precision"||o==="shadowSide"||o==="uniformsGroups"||o==="uniformsNeedUpdate"||o==="userData"||o==="version"||o==="wireframeLinecap"||o==="wireframeLinejoin"||o==="wireframeLinewidth"||o.slice(0,4)==="clip"||o.slice(0,7)==="polygon"||o.slice(0,7)==="stencil"||o.slice(0,2)==="is")}function r_(o){switch(o){case"Alpha Map":return"alphaMap";case"Anisotropy Map":return"anisotropyMap";case"AO Map":return"aoMap";case"Bump Map":return"bumpMap";case"Clearcoat Map":return"clearcoatMap";case"Clearcoat Normal Map":return"clearcoatNormalMap";case"Clearcoat Roughness Map":return"clearcoatRoughnessMap";case"Displacement Map":return"displacementMap";case"Emissive Map":return"emissiveMap";case"Gradient Map":return"gradientMap";case"Iridescence Map":return"iridescenceMap";case"Iridescence Thickness Map":return"iridescenceThicknessMap";case"Map":return"map";case"Matcap":return"matcap";case"Normal Map":return"normalMap";case"Roughness Map":return"roughnessMap";case"Sheen Color Map":return"sheenColorMap";case"Sheen Roughness Map":return"sheenRoughnessMap";case"Specular Color Map":return"specularColorMap";case"Specular Map Intensity":return"specularIntensityMap";case"Thickness Map":return"thicknessMap";case"Transmission Map":return"transmissionMap"}return o}function dl(o){switch(o){case"alphaHash":return"Alpha Hash";case"alphaMap":return"Alpha Map";case"alphaToCoverage":return"Alpha To Coverage";case"anisotropy":return"Anisotropy";case"anisotropyMap":return"Anisotropy Map";case"anisotropyRotation":return"Anisotropy Rotation";case"aoMap":return"AO Map";case"aoMapIntensity":return"AO Map Intensity";case"attenuationColor":return"Attenuation Color";case"attenuationDistance":return"Attenuation Distance";case"blendAlpha":return"Blend Alpha";case"blendColor":return"Blend Color";case"blendDst":return"Blend Dst";case"blendDstAlpha":return"Blend Dst Alha";case"blendEquation":return"Blend Equation";case"blendEquationAlpha":return"Blend Equation Alpha";case"blending":return"Blending";case"blendSrc":return"Blend Src";case"blendSrcAlpha":return"Blend Src Alpha";case"bumpMap":return"Bump Map";case"bumpScale":return"Bump Scale";case"clearcoat":return"Clearcoat";case"clearcoatMap":return"Clearcoat Map";case"clearcoatNormalMap":return"Clearcoat Normal Map";case"clearcoatNormalScale":return"Clearcoat Normal Scale";case"clearcoatRoughness":return"Clearcoat Roughness";case"clearcoatRoughnessMap":return"Clearcoat Roughness Map";case"color":return"Color";case"colorWrite":return"Color Write";case"defines":return"Defines";case"depthFunc":return"Depth Func";case"depthTest":return"Depth Test";case"depthWrite":return"Depth Write";case"dispersion":return"Dispersion";case"displacementBias":return"Displacement Bias";case"displacementMap":return"Displacement Map";case"displacementScale":return"Displacement Scale";case"dithering":return"Dithering";case"emissive":return"Emissive";case"emissiveMap":return"Emissive Map";case"emissiveIntensity":return"Emissive Intensity";case"envMap":return"Environment Map";case"envMapIntensity":return"Environment Map Intensity";case"envMapRotation":return"Environment Map Rotation";case"extensions":return"Extensions";case"flatShading":return"Flat Shading";case"fragmentShader":return"Fragment Shader";case"fog":return"Fog";case"glslVersion":return"GLSL Version";case"gradientMap":return"Gradient Map";case"ior":return"IOR";case"iridescence":return"Iridescence";case"iridescenceIOR":return"Iridescence IOR";case"iridescenceMap":return"Iridescence Map";case"iridescenceThicknessMap":return"Iridescence Thickness Map";case"iridescenceThicknessRange":return"Iridescence Thickness Range";case"lights":return"Lights";case"lightMap":return"Light Map";case"lightMapIntensity":return"Light Map Intensity";case"map":return"Map";case"matcap":return"Matcap";case"metalness":return"Metalness";case"metalnessMap":return"Metalness Map";case"name":return"Name";case"normalMap":return"Normal Map";case"normalScale":return"Normal Scale";case"premultipliedAlpha":return"Premultiplied Alpha";case"opacity":return"Opacity";case"reflectivity":return"Reflectivity";case"refractionRatio":return"Refraction Ratio";case"roughness":return"Roughness";case"roughnessMap":return"Roughness Map";case"sheen":return"Sheen";case"sheenColor":return"Sheen Color";case"sheenColorMap":return"Sheen Color Map";case"sheenRoughness":return"Sheen Roughness";case"sheenRoughnessMap":return"Sheen Roughness Map";case"shininess":return"Shininess";case"side":return"Side";case"size":return"Size";case"sizeAttenuation":return"Size Attenuation";case"specular":return"Specular";case"specularColor":return"Specular Color";case"specularColorMap":return"Specular Color Map";case"specularIntensity":return"Specular Intensity";case"specularIntensityMap":return"Specular Map Intensity";case"thickness":return"Thickness";case"thicknessMap":return"Thickness Map";case"toneMapped":return"Tone Mapped";case"transmission":return"Transmission";case"transmissionMap":return"Transmission Map";case"transparent":return"Transparent";case"type":return"Type";case"uuid":return"UUID";case"uniforms":return"Uniforms";case"vertexColors":return"Vertex Colors";case"vertexShader":return"Vertex Shader";case"visible":return"Visible";case"wireframe":return"Wireframe"}return o}function _m(o){const e=o.toLowerCase();return e.search("intensity")>-1||e==="anisotropyrotation"||e==="blendalpha"||e==="bumpscale"||e==="clearcoatroughness"||e==="displacementbias"||e==="displacementscale"||e==="metalness"||e==="opacity"||e==="reflectivity"||e==="refractionratio"||e==="roughness"||e==="sheenroughness"}function o_(){const o=document.createElement("input");return o.type="file",new Promise((e,t)=>{o.addEventListener("change",function(){if(o.files===null)t();else{const s=o.files[0],i=new FileReader;i.onload=function(n){e(n.target.result)},i.readAsDataURL(s)}}),o.click()})}const a_=[{title:"Front",value:y.FrontSide},{title:"Back",value:y.BackSide},{title:"Double",value:y.DoubleSide}],l_=[{title:"No Blending",value:y.NoBlending},{title:"Normal",value:y.NormalBlending},{title:"Additive",value:y.AdditiveBlending},{title:"Subtractive",value:y.SubtractiveBlending},{title:"Multiply",value:y.MultiplyBlending},{title:"Custom",value:y.CustomBlending}],c_=[{title:"Add",value:y.AddEquation},{title:"Subtract",value:y.SubtractEquation},{title:"Reverse Subtract",value:y.ReverseSubtractEquation},{title:"Min",value:y.MinEquation},{title:"Max",value:y.MaxEquation}],h_=[{title:"Zero",value:y.ZeroFactor},{title:"One",value:y.OneFactor},{title:"Src Color",value:y.SrcColorFactor},{title:"One Minus Src Color",value:y.OneMinusSrcColorFactor},{title:"Src Alpha",value:y.SrcAlphaFactor},{title:"One Minus Src Alpha",value:y.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:y.DstAlphaFactor},{title:"One Minus Dst Alpha",value:y.OneMinusDstAlphaFactor},{title:"Dst Color",value:y.DstColorFactor},{title:"One Minus Dst Color",value:y.OneMinusDstColorFactor},{title:"Src Alpha Saturate",value:y.SrcAlphaSaturateFactor},{title:"Constant Color",value:y.ConstantColorFactor},{title:"One Minus Constant Color",value:y.OneMinusConstantColorFactor},{title:"Constant Alpha",value:y.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:y.OneMinusConstantAlphaFactor}],u_=[{title:"Zero",value:y.ZeroFactor},{title:"One",value:y.OneFactor},{title:"Src Color",value:y.SrcColorFactor},{title:"One Minus Src Color",value:y.OneMinusSrcColorFactor},{title:"Src Alpha",value:y.SrcAlphaFactor},{title:"One Minus Src Alpha",value:y.OneMinusSrcAlphaFactor},{title:"Dst Alpha",value:y.DstAlphaFactor},{title:"One Minus Dst Alpha",value:y.OneMinusDstAlphaFactor},{title:"Dst Color",value:y.DstColorFactor},{title:"One Minus Dst Color",value:y.OneMinusDstColorFactor},{title:"Constant Color",value:y.ConstantColorFactor},{title:"One Minus Constant Color",value:y.OneMinusConstantColorFactor},{title:"Constant Alpha",value:y.ConstantAlphaFactor},{title:"One Minus Constant Alpha",value:y.OneMinusConstantAlphaFactor}];function Cr(o,e){o.needsUpdate=!0,o.type="option",o.options=e}function d_(o,e,t,s){return{type:"boolean",title:dl(o),prop:o,value:e,needsUpdate:!0,onChange:(i,n)=>{s.updateObject(t.uuid,`material.${o}`,n),s.updateObject(t.uuid,"material.needsUpdate",!0);const r=s.getScene(t.uuid);if(r!==null){const a=r.getObjectByProperty("uuid",t.uuid);Ye(a,`material.${o}`,n)}}}}function p_(o,e,t,s){const i={type:"number",title:dl(o),prop:o,value:e,min:void 0,max:void 0,step:.01,needsUpdate:!0,onChange:(n,r)=>{s.updateObject(t.uuid,`material.${o}`,r),s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",t.uuid);Ye(l,`material.${o}`,r)}}};switch(o){case"blending":Cr(i,l_);break;case"blendDst":Cr(i,u_);break;case"blendEquation":Cr(i,c_);break;case"blendSrc":Cr(i,h_);break;case"side":Cr(i,a_);break}return _m(o)&&(i.value=Number(e),i.type="range",i.min=Math.min(0,i.value),i.max=Math.max(1,i.value),i.step=.01),i}function f_(o,e,t,s){const i={type:"string",title:dl(o),prop:o,value:e,needsUpdate:!0,onChange:(r,a)=>{s.updateObject(t.uuid,`material.${o}`,a),s.updateObject(t.uuid,"material.needsUpdate",!0);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);Ye(c,`material.${o}`,a)}},onKeyDown:r=>{}};return(o==="vertexShader"||o==="fragmentShader")&&(i.type="field",i.disabled=!1,i.latest=i.value,i.onChange=(r,a)=>{i.latest=a,s.updateObject(t.uuid,`material.${o}`,a);const l=s.getScene(t.uuid);if(l!==null){const c=l.getObjectByProperty("uuid",t.uuid);Ye(c,`material.${o}`,a)}},i.onKeyDown=r=>{if(r.key==="Enter"&&(r.altKey||r.metaKey)){s.updateObject(t.uuid,"material.needsUpdate",!0);const a=s.getScene(t.uuid);if(a!==null){const l=a.getObjectByProperty("uuid",t.uuid);Ye(l,"material.needsUpdate",!0)}}}),i}function m_(o){return o.x!==void 0&&o.y!==void 0&&o.z===void 0}function g_(o){return o.x!==void 0&&o.y!==void 0&&o.z!==void 0&&o.w===void 0}function y_(o){return o.x!==void 0&&o.y!==void 0&&o.z!==void 0&&o.w!==void 0}function mh(o){o.sort((e,t)=>e.title<t.title?-1:e.title>t.title?1:0)}function Jr(o,e,t,s,i="",n=!1){const r=dl(o).split(".")[0].replaceAll("[","").replaceAll("]",""),a=i.length>0?`${i}.${o}`:o,l=typeof e;if(l==="boolean"||l==="string")return{title:r,prop:a,type:l,value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(l==="number"){const c={title:r,prop:a,type:"number",value:e,step:.01,disabled:n,onChange:(h,u)=>{s.updateObject(t.uuid,`material.${a}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);Ye(p,`material.${a}`,u)}}};return _m(r)&&(c.type="range",c.min=0,c.max=1),c}else{if(e.isColor)return{title:r,prop:a,type:"color",value:e,disabled:n,onChange:(c,h)=>{const u=new y.Color(h);s.updateObject(t.uuid,`material.${a}`,u);const d=s.getScene(t.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",t.uuid);Ye(p,`material.${a}`,u)}}};if(Array.isArray(e)){const c=[];for(const h in e){const u=e[h],d=`[${h.toString()}]`;if(u.value!==void 0){const p=Jr(`${d}.value`,u.value,t,s,a,n);p!==void 0&&c.push(p)}else{const p=Jr(d,u,t,s,a,n);p!==void 0&&c.push(p)}}if(c.length>0)return mh(c),{title:r,items:c}}else{if(m_(e))return{title:r,prop:a,type:"vector2",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(g_(e))return{title:r,prop:a,type:"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(y_(e))return{title:r,prop:a,type:"grid4",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(e.isEuler)return{title:r,prop:a,type:"euler",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};if(e.src!==void 0)return{title:r,type:"image",value:e,disabled:n,onChange:(c,h)=>{const u=r_(o),d=i.length>0?`${i}.${u}`:u;s.createTexture(t.uuid,`material.${d}`,h);const p=s.getScene(t.uuid);if(p!==null){const f=p.getObjectByProperty("uuid",t.uuid);if(f!==void 0){const m=x=>{const g=f.material,_=d.split(".");switch(_.length){case 1:g[_[0]]=x;break;case 2:g[_[0]][_[1]]=x;break;case 3:g[_[0]][_[1]][_[2]]=x;break;case 4:g[_[0]][_[1]][_[2]][_[3]]=x;break;case 5:g[_[0]][_[1]][_[2]][_[3]][_[4]]=x;break}g.needsUpdate=!0};h.src.length>0?pm(h.src).then(x=>{x.offset.set(h.offset[0],h.offset[1]),x.repeat.set(h.repeat[0],h.repeat[1]),m(x)}):m(null)}}}};if(e.elements!==void 0)return{title:r,prop:a,type:e.elements.length>9?"grid4":"grid3",value:e,disabled:n,onChange:(c,h)=>{s.updateObject(t.uuid,`material.${a}`,h);const u=s.getScene(t.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",t.uuid);Ye(d,`material.${a}`,h)}}};{const c=[],h=o==="defines"||o==="extensions";try{for(const u in e){const d=e[u];if(d!==void 0)if(d.value!==void 0){const p=Jr(`${u}.value`,d.value,t,s,a,h);p!==void 0&&c.push(p)}else{const p=Jr(u,d,t,s,a,h);p!==void 0&&c.push(p)}}}catch{console.log("Hermes - Issue cycling through material object:",o,e)}if(c.length>0)return mh(c),{title:r,items:c}}}}}function Ed(o,e,t){const s=[];for(const i in o){if(!n_(i))continue;const n=typeof o[i],r=o[i];if(n==="boolean")s.push(d_(i,r,e,t));else if(n==="number")s.push(p_(i,r,e,t));else if(n==="string")s.push(f_(i,r,e,t));else if(n==="object"){const a=Jr(i,r,e,t);a!==void 0&&s.push(a)}else r!==void 0&&console.log("Hermes - Other Material Prop Type:",i,n,r)}return mh(s),s.push({title:"Update Material",type:"button",onChange:()=>{t.updateObject(e.uuid,"material.needsUpdate",!0);const i=t.getScene(e.uuid);if(i!==null){const n=i.getObjectByProperty("uuid",e.uuid);Ye(n,"material.needsUpdate",!0)}}}),s}function x_(o,e){function t(){return`${e.name}_material`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=o.material;if(Array.isArray(r)){const a=[],l=r.length;for(let c=0;c<l;c++)a.push(E.jsx(hs,{three:e,title:`Material ${c}`,items:Ed(r[c],o,e)},`Material ${c}`));return E.jsx(E.Fragment,{children:a})}else return E.jsx(hs,{three:e,title:"Material",items:Ed(r,o,e),expanded:i,onToggle:a=>{n(a)}})}const Ad="data:image/gif;base64,R0lGODlhDgFkAIAAAP///wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDIgNzkuZGJhM2RhM2I1LCAyMDIzLzEyLzE1LTEwOjQyOjM3ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjUuNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyMDk3M0NEODAxQjQxMUVGODVGNENDMkUyMUExNDk1NSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMDk3M0NEOTAxQjQxMUVGODVGNENDMkUyMUExNDk1NSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkE4ODc3Qzg5MDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkE4ODc3QzhBMDFCMzExRUY4NUY0Q0MyRTIxQTE0OTU1Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+Af/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAIfkEAAAAAAAsAAAAAA4BZAAAAv+Mj6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqTkJAGDQ+dnpuekmGgAKejpKuiZqmprKqoZKGyrbOlqrejub6xvLGyw8TFzcprurGuvqybxq7ETbrItsCz0l7Zpc+6p9/cS967w9/S2FTF0u/mzehK4Oqz3eTl9vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxo0XHDt6/AgypMiRJEuaPIkypcqVLFt+KwAAOw==";function __(o){const e=o.step!==void 0?o.step:.01,t=W.useRef(null),s=W.useRef(null),i=W.useRef(null),n=W.useRef(null),r=W.useRef(null),[a]=W.useState(o.value),[l,c]=W.useState(o.value.offset[0]),[h,u]=W.useState(o.value.offset[1]),[d,p]=W.useState(o.value.repeat[0]),[f,m]=W.useState(o.value.repeat[1]);function x(_,b,T,S,C){if(o.onChange!==void 0){const w=o.prop!==void 0?o.prop:o.title;o.onChange(w,{src:_,offset:[b,T],repeat:[S,C]})}}function g(_){const b=t.current.src,T=_.target.value;switch(_.target){case s.current:c(T),x(b,T,h,d,f);break;case i.current:u(T),x(b,l,T,d,f);break;case n.current:p(T),x(b,l,h,T,f);break;case r.current:m(T),x(b,l,h,d,T);break}}return E.jsxs("div",{className:"imageField",children:[E.jsx("img",{alt:o.title,ref:t,onClick:()=>{o_().then(_=>{t.current.src=_,x(_,l,h,d,f)})},src:a.src.length>0?a.src:Ad}),E.jsxs("div",{className:"fields",children:[E.jsxs("div",{children:[E.jsx("span",{children:"Offset:"}),E.jsx("input",{ref:s,type:"number",value:l,step:e,name:ht(),onChange:g}),E.jsx("input",{ref:i,type:"number",value:h,step:e,name:ht(),onChange:g})]}),E.jsxs("div",{children:[E.jsx("span",{children:"Repeat:"}),E.jsx("input",{ref:n,type:"number",value:d,step:e,name:ht(),onChange:g}),E.jsx("input",{ref:r,type:"number",value:f,step:e,name:ht(),onChange:g})]}),E.jsx("button",{onClick:()=>{x("",l,h,d,f),t.current.src=Ad},children:"Clear"})]})]})}function Ra(o){let e=o.value;e!==void 0&&(e.isColor!==void 0?e=uh(o.value):o.type==="color"&&(e=uh(new y.Color().setStyle(o.value,y.LinearSRGBColorSpace))));const[t,s]=W.useState(e),i=W.useRef(null),n=c=>{let h=c.target.value;if(o.type==="boolean")h=c.target.checked;else if(o.type==="option"&&(typeof o.value=="number"?h=Number(h):typeof o.value=="boolean"?h=!!h:typeof o.value=="object"&&(h=JSON.parse(h)),o.options!==void 0)){const u=o.options.length;for(let d=0;d<u&&o.options[d].value!==h;d++);}s(h),o.onChange!==void 0&&o.onChange(o.prop!==void 0?o.prop:o.title,h)},r={};o.disabled&&(r.opacity=.8);const a=o.type==="field"||o.type==="string"&&(t.length>100||t.search(`
|
|
50
|
+
`)>-1),l=a||o.type==="image"||o.type==="vector2";return E.jsxs("div",{className:`field ${l?"block":""}`,style:r,children:[o.type!=="button"&&E.jsx("span",{ref:i,children:yo(o.title)},"fieldLabel"),o.type==="string"&&!a&&E.jsx("input",{type:"text",disabled:o.disabled,onChange:n,value:t,name:ht()}),(o.type==="field"||o.type==="string"&&a)&&E.jsx("textarea",{cols:50,rows:10,disabled:o.disabled!==void 0?o.disabled:!0,onChange:n,onKeyDown:c=>{o.onKeyDown!==void 0&&o.onKeyDown(c)},value:t,name:ht()}),o.type==="boolean"&&E.jsx("input",{type:"checkbox",disabled:o.disabled,onChange:n,checked:t,name:ht()}),o.type==="number"&&E.jsx(hn,{value:t,type:o.type,prop:o.prop!==void 0?o.prop:o.title,min:o.min,max:o.max,step:o.step,disabled:o.disabled,labelRef:i,onChange:o.onChange}),o.type==="range"&&E.jsx(hn,{value:t,type:o.type,prop:o.prop!==void 0?o.prop:o.title,min:o.min,max:o.max,step:o.step,disabled:o.disabled,labelRef:i,onChange:o.onChange}),o.type==="color"&&E.jsxs(E.Fragment,{children:[E.jsx("input",{type:"text",value:t.toString(),onChange:n,disabled:o.disabled,className:"color",name:ht()}),E.jsx("input",{type:"color",value:t,onChange:n,disabled:o.disabled,name:ht()})]}),o.type==="button"&&E.jsx("button",{disabled:o.disabled,onClick:()=>{o.onChange!==void 0&&o.onChange(o.prop!==void 0?o.prop:o.title,!0)},children:o.title}),o.type==="image"&&E.jsx(__,{title:o.title,prop:o.prop,value:o.value,onChange:o.onChange}),o.type==="option"&&E.jsx(E.Fragment,{children:E.jsx("select",{onChange:n,disabled:o.disabled,defaultValue:o.value,name:ht(),children:o.options?.map((c,h)=>E.jsx("option",{value:c.value,children:yo(c.title)},h))})}),o.type==="vector2"&&E.jsx(Vx,{step:o.step,value:t,min:0,max:1,onChange:n}),o.type==="grid3"&&E.jsx(Cd,{step:o.step,value:t,onChange:n}),o.type==="grid4"&&E.jsx(i_,{step:o.step,value:t,onChange:n}),o.type==="euler"&&E.jsx(Cd,{step:o.step,value:t,onChange:n})]})}function b_(o){return"items"in o}class hs extends W.Component{subgroupNames=[];subgroupElements=[];valueOverrides=new Map;three;constructor(e){super(e),this.three=e.three,this.state={lastUpdated:Date.now()}}addGroup(e){const t=[];e.items.forEach(n=>{t.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(r,a)=>{e.onUpdate(r,a)}})});const s=W.createRef(),i=E.jsx(hs,{three:this.props.three,ref:s,title:e.title,expanded:e.expanded,items:t},Math.random());return this.subgroupNames.push(e.title),this.subgroupElements.push(i),this.setState({lastUpdated:Date.now()}),s}removeGroup(e){const t=this.subgroupNames.length;for(let s=0;s<t;s++){const i=this.subgroupNames[s];if(e===i){this.subgroupNames.splice(s,1),this.subgroupElements.splice(s,1),this.setState({lastUpdated:Date.now()});return}}}setField(e,t){this.valueOverrides.set(e,t),this.setState({lastUpdated:Date.now()})}render(){const e=[];return this.props.items.forEach(t=>{if(b_(t))e.push(E.jsx(hs,{three:this.props.three,title:yo(t.title),items:t.items},Math.random()));else{const s=this.valueOverrides.get(t.title),i=s!==void 0?s:t.value;e.push(E.jsx(Ra,{title:t.title,prop:t.prop,value:i,type:t.type,min:t.min,max:t.max,step:t.step,disabled:t.disabled,options:t.options,onChange:(n,r)=>{t.onChange!==void 0&&(this.valueOverrides.delete(t.title),t.onChange(n,r))},onKeyDown:n=>{t.onKeyDown!==void 0&&t.onKeyDown(n)}},Math.random()))}}),this.subgroupElements.forEach(t=>e.push(t)),E.jsx(Qn,{three:this.props.three,label:this.props.title,open:this.props.expanded===!0,onToggle:t=>{this.props.onToggle&&this.props?.onToggle(t)},children:e})}}class Ne extends W.Component{static instance;static groups=[];static groupsRefs=[];static groupTitles=[];static three;constructor(e){super(e),this.state={lastUpdate:Date.now()},Ne.instance=this,Ne.three=e.three,e.three.addEventListener(ce.ADD_GROUP,this.addGroup),e.three.addEventListener(ce.REMOVE_GROUP,this.removeGroup)}componentWillUnmount(){this.props.three.removeEventListener(ce.ADD_GROUP,this.addGroup),this.props.three.removeEventListener(ce.REMOVE_GROUP,this.removeGroup)}render(){return E.jsx("div",{className:"customGroups",children:Ne.groups},this.state.lastUpdate)}addGroup=e=>{const t=JSON.parse(e.value),s=[];t.items.forEach(i=>{s.push({type:i.type,prop:i.prop,title:i.title!==void 0?i.title:i.prop,value:i.value,min:i.min,max:i.max,step:i.step,options:i.options,disabled:i.disabled,onChange:(n,r)=>{this.props.three.updateGroup(t.title,n,r)}})}),Ne.groups.push(E.jsx(hs,{three:this.props.three,title:t.title,items:s},Math.random())),Ne.groupTitles.push(t.title),this.setState({lastUpdate:Date.now()})};removeGroup=e=>{const t=e.value,s=Ne.groupTitles.length;for(let i=0;i<s;i++)if(t===Ne.groupTitles[i]){Ne.groups.splice(i,1),Ne.groupTitles.splice(i,1),this.setState({lastUpdate:Date.now()});return}};static addEditorGroup(e){const t=[];e.items.forEach(n=>{t.push({type:n.type,prop:n.prop,title:n.title!==void 0?n.title:n.prop,value:n.value,min:n.min,max:n.max,step:n.step,options:n.options,disabled:n.disabled,onChange:(r,a)=>{e.onUpdate(r,a)}})});const s=W.createRef(),i=E.jsx(hs,{three:Ne.three,ref:s,title:e.title,items:t},Math.random());return Ne.groups.push(i),Ne.groupsRefs.push(s),Ne.groupTitles.push(e.title),s}static removeEditorGroup(e){const t=Ne.groupTitles.length;for(let s=0;s<t;s++)if(e===Ne.groupTitles[s]){Ne.groups.splice(s,1),Ne.groupTitles.splice(s,1),Ne.instance.setState({lastUpdate:Date.now()});return}}static removeAllGroups(){for(let e=Ne.groupTitles.length;e>0;e--)Ne.groups.splice(e,1),Ne.groupTitles.splice(e,1);Ne.instance.setState({lastUpdate:Date.now()})}}function Rd(o){switch(o){case"fov":return"FOV";case"zoom":return"Zoom";case"near":return"Near";case"far":return"Far";case"focus":return"Focus";case"aspect":return"Aspect";case"filmGauge":return"Film Gauge";case"filmOffset":return"Film Offset";case"left":return"Left";case"right":return"Right";case"top":return"Top";case"bottom":return"Bottom"}return o}function T_(o,e){function t(){return`${e.name}_camera`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=[];if(o.perspectiveCameraInfo!==void 0)for(const a in o.perspectiveCameraInfo)r.push({title:Rd(a),prop:a,type:"number",step:.01,value:o.perspectiveCameraInfo[a],onChange:(l,c)=>{e.updateObject(o.uuid,l,c),e.requestMethod(o.uuid,"updateProjectionMatrix");const h=e.getScene(o.uuid);if(h!==null){const u=h.getObjectByProperty("uuid",o.uuid);u!==void 0&&(Ye(u,l,c),u.updateProjectionMatrix())}}});else if(o.orthographicCameraInfo!==void 0)for(const a in o.orthographicCameraInfo)r.push({title:Rd(a),prop:a,type:"number",step:.01,value:o.orthographicCameraInfo[a],onChange:(l,c)=>{e.updateObject(o.uuid,l,c),e.requestMethod(o.uuid,"updateProjectionMatrix");const h=e.getScene(o.uuid);if(h!==null){const u=h.getObjectByProperty("uuid",o.uuid);u!==void 0&&(Ye(u,l,c),u.updateProjectionMatrix())}}});return E.jsx(hs,{three:e,title:"Camera",items:r,expanded:i,onToggle:a=>{n(a)}})}class S_{constructor(e,t){this.nodes=e,this.info=t,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this._animationLoop!==null&&this._animationLoop(t,s)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class vs{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let s=this.weakMap;for(let i=0;i<e.length-1;i++){const n=e[i];s.has(n)===!1&&s.set(n,new WeakMap),s=s.get(n)}return s.set(e[e.length-1],t),this}delete(e){let t=this.weakMap;for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),t===void 0)return!1;return t.delete(e[e.length-1])}}const bm="177",v_=0,w_=1,M_=2,C_=0,E_=1,Na=3,Qs=0,Gt=1,Jn=2,hr=0,Js=1,$a=2,ja=3,qa=4,lo=5,bs=100,Tm=101,Sm=102,A_=103,R_=104,vi=200,vm=201,wm=202,Mm=203,Ya=204,Xa=205,Cm=206,Em=207,Am=208,Rm=209,Nm=210,Pm=0,Fm=1,Dm=2,Za=3,Om=4,Bm=5,Im=6,Lm=7,pl=0,N_=1,P_=2,er=0,F_=1,D_=2,O_=3,B_=4,I_=6,L_=7,tu=300,xo=301,Ka=302,su=303,iu=304,gh=306,ur=1e3,Ri=1001,dr=1002,ut=1003,Um=1004,_o=1005,Qt=1006,yh=1007,ei=1008,Nt=1009,co=1010,ho=1011,jn=1012,Et=1013,Xe=1014,Kt=1015,rs=1016,U_=1017,k_=1018,Fi=1020,km=35902,z_=1021,nu=1022,os=1023,Bs=1026,ti=1027,ru=1028,ou=1029,cn=1030,au=1031,G_=1032,lu=1033,Hl=33776,Pa=33777,Fa=33778,Da=33779,Nd=35840,Pd=35841,Fd=35842,Dd=35843,Od=36196,xh=37492,_h=37496,bh=37808,Th=37809,Sh=37810,vh=37811,wh=37812,Mh=37813,Ch=37814,Eh=37815,Ah=37816,Rh=37817,Nh=37818,Ph=37819,Fh=37820,Dh=37821,Wl=36492,V_=36283,Bd=36284,Id=36285,Ld=36286,Di=0,H_=1,ri="",Xt="srgb",tr="srgb-linear",Qa="linear",te="srgb",W_=0,en=7680,$_=7681,j_=7682,q_=7683,Y_=34055,X_=34056,Z_=5386,K_=512,Q_=513,J_=514,eb=515,tb=516,sb=517,ib=518,Oh=519,zm=512,cu=513,Gm=514,Vm=515,Hm=516,Wm=517,$m=518,jm=519,Ja=35044,qn=35048,Ut=2e3,Oi=2001;class Ht{constructor(e,t,s,i,n,r,a,l,c){Ht.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,i,n,r,a,l,c)}set(e,t,s,i,n,r,a,l,c){const h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=n,h[5]=l,h[6]=s,h[7]=r,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const 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){const s=e.elements,i=t.elements,n=this.elements,r=s[0],a=s[3],l=s[6],c=s[1],h=s[4],u=s[7],d=s[2],p=s[5],f=s[8],m=i[0],x=i[3],g=i[6],_=i[1],b=i[4],T=i[7],S=i[2],C=i[5],w=i[8];return n[0]=r*m+a*_+l*S,n[3]=r*x+a*b+l*C,n[6]=r*g+a*T+l*w,n[1]=c*m+h*_+u*S,n[4]=c*x+h*b+u*C,n[7]=c*g+h*T+u*w,n[2]=d*m+p*_+f*S,n[5]=d*x+p*b+f*C,n[8]=d*g+p*T+f*w,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8];return t*r*h-t*a*c-s*n*h+s*a*l+i*n*c-i*r*l}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=h*r-a*c,d=a*l-h*n,p=c*n-r*l,f=t*u+s*d+i*p;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return e[0]=u*m,e[1]=(i*c-h*s)*m,e[2]=(a*s-i*r)*m,e[3]=d*m,e[4]=(h*t-i*l)*m,e[5]=(i*n-a*t)*m,e[6]=p*m,e[7]=(s*l-c*t)*m,e[8]=(r*t-s*n)*m,this}transpose(){let e;const 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){const 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,s,i,n,r,a){const l=Math.cos(n),c=Math.sin(n);return this.set(s*l,s*c,-s*(l*r+c*a)+r+e,-i*c,i*l,-i*(-c*r+l*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply($l.makeScale(e,t)),this}rotate(e){return this.premultiply($l.makeRotation(-e)),this}translate(e,t){return this.premultiply($l.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){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<9;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const $l=new Ht;function qm(o){for(let e=o.length-1;e>=0;--e)if(o[e]>=65535)return!0;return!1}function Bh(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function nb(){const o=Bh("canvas");return o.style.display="block",o}const Ud={};function oi(o){o in Ud||(Ud[o]=!0,console.warn(o))}const kd=new Ht().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),zd=new Ht().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function rb(){const o={enabled:!0,workingColorSpace:tr,spaces:{},convert:function(i,n,r){return this.enabled===!1||n===r||!n||!r||(this.spaces[n].transfer===te&&(i.r=si(i.r),i.g=si(i.g),i.b=si(i.b)),this.spaces[n].primaries!==this.spaces[r].primaries&&(i.applyMatrix3(this.spaces[n].toXYZ),i.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===te&&(i.r=sr(i.r),i.g=sr(i.g),i.b=sr(i.b))),i},workingToColorSpace:function(i,n){return this.convert(i,this.workingColorSpace,n)},colorSpaceToWorking:function(i,n){return this.convert(i,n,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ri?Qa:this.spaces[i].transfer},getLuminanceCoefficients:function(i,n=this.workingColorSpace){return i.fromArray(this.spaces[n].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,n,r){return i.copy(this.spaces[n].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,n){return oi("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(i,n)},toWorkingColorSpace:function(i,n){return oi("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(i,n)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],s=[.3127,.329];return o.define({[tr]:{primaries:e,whitePoint:s,transfer:Qa,toXYZ:kd,fromXYZ:zd,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Xt},outputColorSpaceConfig:{drawingBufferColorSpace:Xt}},[Xt]:{primaries:e,whitePoint:s,transfer:te,toXYZ:kd,fromXYZ:zd,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Xt}}}),o}const Ue=rb();function si(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function sr(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}const Ym={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},di={h:0,s:0,l:0},Lo={h:0,s:0,l:0};function jl(o,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?o+(e-o)*6*t:t<1/2?e:t<2/3?o+(e-o)*6*(2/3-t):o}class ve{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(t===void 0&&s===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Xt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ue.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Ue.workingColorSpace){return this.r=e,this.g=t,this.b=s,Ue.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Ue.workingColorSpace){if(e=eu(e,1),t=pe(t,0,1),s=pe(s,0,1),t===0)this.r=this.g=this.b=s;else{const n=s<=.5?s*(1+t):s+t-s*t,r=2*s-n;this.r=jl(r,n,e+1/3),this.g=jl(r,n,e),this.b=jl(r,n,e-1/3)}return Ue.colorSpaceToWorking(this,i),this}setStyle(e,t=Xt){function s(n){n!==void 0&&parseFloat(n)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let n;const r=i[1],a=i[2];switch(r){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setRGB(Math.min(255,parseInt(n[1],10))/255,Math.min(255,parseInt(n[2],10))/255,Math.min(255,parseInt(n[3],10))/255,t);if(n=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setRGB(Math.min(100,parseInt(n[1],10))/100,Math.min(100,parseInt(n[2],10))/100,Math.min(100,parseInt(n[3],10))/100,t);break;case"hsl":case"hsla":if(n=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(n[4]),this.setHSL(parseFloat(n[1])/360,parseFloat(n[2])/100,parseFloat(n[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(r===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(r===6)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Xt){const s=Ym[e.toLowerCase()];return s!==void 0?this.setHex(s,t):console.warn("THREE.Color: Unknown color "+e),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=si(e.r),this.g=si(e.g),this.b=si(e.b),this}copyLinearToSRGB(e){return this.r=sr(e.r),this.g=sr(e.g),this.b=sr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return Ue.workingToColorSpace(xt.copy(this),e),Math.round(pe(xt.r*255,0,255))*65536+Math.round(pe(xt.g*255,0,255))*256+Math.round(pe(xt.b*255,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ue.workingColorSpace){Ue.workingToColorSpace(xt.copy(this),t);const s=xt.r,i=xt.g,n=xt.b,r=Math.max(s,i,n),a=Math.min(s,i,n);let l,c;const h=(a+r)/2;if(a===r)l=0,c=0;else{const u=r-a;switch(c=h<=.5?u/(r+a):u/(2-r-a),r){case s:l=(i-n)/u+(i<n?6:0);break;case i:l=(n-s)/u+2;break;case n:l=(s-i)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Ue.workingColorSpace){return Ue.workingToColorSpace(xt.copy(this),t),e.r=xt.r,e.g=xt.g,e.b=xt.b,e}getStyle(e=Xt){Ue.workingToColorSpace(xt.copy(this),e);const t=xt.r,s=xt.g,i=xt.b;return e!==Xt?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(s*255)},${Math.round(i*255)})`}offsetHSL(e,t,s){return this.getHSL(di),this.setHSL(di.h+e,di.s+t,di.l+s)}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,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(di),e.getHSL(Lo);const s=Pi(di.h,Lo.h,t),i=Pi(di.s,Lo.s,t),n=Pi(di.l,Lo.l,t);return this.setHSL(s,i,n),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,n=e.elements;return this.r=n[0]*t+n[3]*s+n[6]*i,this.g=n[1]*t+n[4]*s+n[7]*i,this.b=n[2]*t+n[5]*s+n[8]*i,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}}const xt=new ve;ve.NAMES=Ym;class fl{constructor(e,t,s,i){fl.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const n=this.elements;return n[0]=e,n[2]=t,n[1]=s,n[3]=i,this}}class xr{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,n,r,a){let l=s[i+0],c=s[i+1],h=s[i+2],u=s[i+3];const d=n[r+0],p=n[r+1],f=n[r+2],m=n[r+3];if(a===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=p,e[t+2]=f,e[t+3]=m;return}if(u!==m||l!==d||c!==p||h!==f){let x=1-a;const g=l*d+c*p+h*f+u*m,_=g>=0?1:-1,b=1-g*g;if(b>Number.EPSILON){const S=Math.sqrt(b),C=Math.atan2(S,g*_);x=Math.sin(x*C)/S,a=Math.sin(a*C)/S}const T=a*_;if(l=l*x+d*T,c=c*x+p*T,h=h*x+f*T,u=u*x+m*T,x===1-a){const S=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=S,c*=S,h*=S,u*=S}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,n,r){const a=s[i],l=s[i+1],c=s[i+2],h=s[i+3],u=n[r],d=n[r+1],p=n[r+2],f=n[r+3];return e[t]=a*f+h*u+l*p-c*d,e[t+1]=l*f+h*d+c*u-a*p,e[t+2]=c*f+h*p+a*d-l*u,e[t+3]=h*f-a*u-l*d-c*p,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,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,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){const s=e._x,i=e._y,n=e._z,r=e._order,a=Math.cos,l=Math.sin,c=a(s/2),h=a(i/2),u=a(n/2),d=l(s/2),p=l(i/2),f=l(n/2);switch(r){case"XYZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"YXZ":this._x=d*h*u+c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"ZXY":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u-d*p*f;break;case"ZYX":this._x=d*h*u-c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u+d*p*f;break;case"YZX":this._x=d*h*u+c*p*f,this._y=c*p*u+d*h*f,this._z=c*h*f-d*p*u,this._w=c*h*u-d*p*f;break;case"XZY":this._x=d*h*u-c*p*f,this._y=c*p*u-d*h*f,this._z=c*h*f+d*p*u,this._w=c*h*u+d*p*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+r)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],n=t[8],r=t[1],a=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=s+a+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(n-c)*p,this._z=(r-i)*p}else if(s>a&&s>u){const p=2*Math.sqrt(1+s-a-u);this._w=(h-l)/p,this._x=.25*p,this._y=(i+r)/p,this._z=(n+c)/p}else if(a>u){const p=2*Math.sqrt(1+a-s-u);this._w=(n-c)/p,this._x=(i+r)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-s-a);this._w=(r-i)/p,this._x=(n+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<Number.EPSILON?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(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=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(pe(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(s===0)return this;const i=Math.min(1,t/s);return this.slerp(e,i),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=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,n=e._z,r=e._w,a=t._x,l=t._y,c=t._z,h=t._w;return this._x=s*h+r*a+i*c-n*l,this._y=i*h+r*l+n*a-s*c,this._z=n*h+r*c+s*l-i*a,this._w=r*h-s*a-i*l-n*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const s=this._x,i=this._y,n=this._z,r=this._w;let a=r*e._w+s*e._x+i*e._y+n*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=r,this._x=s,this._y=i,this._z=n,this;const l=1-a*a;if(l<=Number.EPSILON){const p=1-t;return this._w=p*r+t*this._w,this._x=p*s+t*this._x,this._y=p*i+t*this._y,this._z=p*n+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,a),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=r*u+this._w*d,this._x=s*u+this._x*d,this._y=i*u+this._y*d,this._z=n*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),n=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),n*Math.sin(t),n*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}}class N{constructor(e=0,t=0,s=0){N.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return s===void 0&&(s=this.z),this.x=e,this.y=t,this.z=s,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 new 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 new 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(Gd.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Gd.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[3]*s+n[6]*i,this.y=n[1]*t+n[4]*s+n[7]*i,this.z=n[2]*t+n[5]*s+n[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,n=e.elements,r=1/(n[3]*t+n[7]*s+n[11]*i+n[15]);return this.x=(n[0]*t+n[4]*s+n[8]*i+n[12])*r,this.y=(n[1]*t+n[5]*s+n[9]*i+n[13])*r,this.z=(n[2]*t+n[6]*s+n[10]*i+n[14])*r,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,n=e.x,r=e.y,a=e.z,l=e.w,c=2*(r*i-a*s),h=2*(a*t-n*i),u=2*(n*s-r*t);return this.x=t+l*c+r*u-a*h,this.y=s+l*h+a*c-n*u,this.z=i+l*u+n*h-r*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i,this.y=n[1]*t+n[5]*s+n[9]*i,this.z=n[2]*t+n[6]*s+n[10]*i,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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this.z=pe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this.z=pe(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,n=e.z,r=t.x,a=t.y,l=t.z;return this.x=i*l-n*a,this.y=n*r-s*l,this.z=s*a-i*r,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return ql.copy(this).projectOnVector(e),this.sub(ql)}reflect(e){return this.sub(ql.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(pe(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}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,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,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(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const ql=new N,Gd=new xr;class Ie{constructor(e,t,s,i,n,r,a,l,c,h,u,d,p,f,m,x){Ie.prototype.isMatrix4=!0,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,s,i,n,r,a,l,c,h,u,d,p,f,m,x)}set(e,t,s,i,n,r,a,l,c,h,u,d,p,f,m,x){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=i,g[1]=n,g[5]=r,g[9]=a,g[13]=l,g[2]=c,g[6]=h,g[10]=u,g[14]=d,g[3]=p,g[7]=f,g[11]=m,g[15]=x,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 Ie().fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const 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,s){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,s=e.elements,i=1/wn.setFromMatrixColumn(e,0).length(),n=1/wn.setFromMatrixColumn(e,1).length(),r=1/wn.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*n,t[5]=s[5]*n,t[6]=s[6]*n,t[7]=0,t[8]=s[8]*r,t[9]=s[9]*r,t[10]=s[10]*r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,n=e.z,r=Math.cos(s),a=Math.sin(s),l=Math.cos(i),c=Math.sin(i),h=Math.cos(n),u=Math.sin(n);if(e.order==="XYZ"){const d=r*h,p=r*u,f=a*h,m=a*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=p+f*c,t[5]=d-m*c,t[9]=-a*l,t[2]=m-d*c,t[6]=f+p*c,t[10]=r*l}else if(e.order==="YXZ"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d+m*a,t[4]=f*a-p,t[8]=r*c,t[1]=r*u,t[5]=r*h,t[9]=-a,t[2]=p*a-f,t[6]=m+d*a,t[10]=r*l}else if(e.order==="ZXY"){const d=l*h,p=l*u,f=c*h,m=c*u;t[0]=d-m*a,t[4]=-r*u,t[8]=f+p*a,t[1]=p+f*a,t[5]=r*h,t[9]=m-d*a,t[2]=-r*c,t[6]=a,t[10]=r*l}else if(e.order==="ZYX"){const d=r*h,p=r*u,f=a*h,m=a*u;t[0]=l*h,t[4]=f*c-p,t[8]=d*c+m,t[1]=l*u,t[5]=m*c+d,t[9]=p*c-f,t[2]=-c,t[6]=a*l,t[10]=r*l}else if(e.order==="YZX"){const d=r*l,p=r*c,f=a*l,m=a*c;t[0]=l*h,t[4]=m-d*u,t[8]=f*u+p,t[1]=u,t[5]=r*h,t[9]=-a*h,t[2]=-c*h,t[6]=p*u+f,t[10]=d-m*u}else if(e.order==="XZY"){const d=r*l,p=r*c,f=a*l,m=a*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+m,t[5]=r*h,t[9]=p*u-f,t[2]=f*u-p,t[6]=a*h,t[10]=m*u+d}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(ob,e,ab)}lookAt(e,t,s){const i=this.elements;return Wt.subVectors(e,t),Wt.lengthSq()===0&&(Wt.z=1),Wt.normalize(),pi.crossVectors(s,Wt),pi.lengthSq()===0&&(Math.abs(s.z)===1?Wt.x+=1e-4:Wt.z+=1e-4,Wt.normalize(),pi.crossVectors(s,Wt)),pi.normalize(),Uo.crossVectors(Wt,pi),i[0]=pi.x,i[4]=Uo.x,i[8]=Wt.x,i[1]=pi.y,i[5]=Uo.y,i[9]=Wt.y,i[2]=pi.z,i[6]=Uo.z,i[10]=Wt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,n=this.elements,r=s[0],a=s[4],l=s[8],c=s[12],h=s[1],u=s[5],d=s[9],p=s[13],f=s[2],m=s[6],x=s[10],g=s[14],_=s[3],b=s[7],T=s[11],S=s[15],C=i[0],w=i[4],R=i[8],P=i[12],z=i[1],$=i[5],q=i[9],j=i[13],X=i[2],Z=i[6],we=i[10],de=i[14],ye=i[3],se=i[7],Me=i[11],ze=i[15];return n[0]=r*C+a*z+l*X+c*ye,n[4]=r*w+a*$+l*Z+c*se,n[8]=r*R+a*q+l*we+c*Me,n[12]=r*P+a*j+l*de+c*ze,n[1]=h*C+u*z+d*X+p*ye,n[5]=h*w+u*$+d*Z+p*se,n[9]=h*R+u*q+d*we+p*Me,n[13]=h*P+u*j+d*de+p*ze,n[2]=f*C+m*z+x*X+g*ye,n[6]=f*w+m*$+x*Z+g*se,n[10]=f*R+m*q+x*we+g*Me,n[14]=f*P+m*j+x*de+g*ze,n[3]=_*C+b*z+T*X+S*ye,n[7]=_*w+b*$+T*Z+S*se,n[11]=_*R+b*q+T*we+S*Me,n[15]=_*P+b*j+T*de+S*ze,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],s=e[4],i=e[8],n=e[12],r=e[1],a=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14],f=e[3],m=e[7],x=e[11],g=e[15];return f*(+n*l*u-i*c*u-n*a*d+s*c*d+i*a*p-s*l*p)+m*(+t*l*p-t*c*d+n*r*d-i*r*p+i*c*h-n*l*h)+x*(+t*c*u-t*a*p-n*r*u+s*r*p+n*a*h-s*c*h)+g*(-i*a*h-t*l*u+t*a*d+i*r*u-s*r*d+s*l*h)}transpose(){const e=this.elements;let 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,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],n=e[3],r=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],x=e[14],g=e[15],_=u*x*c-m*d*c+m*l*p-a*x*p-u*l*g+a*d*g,b=f*d*c-h*x*c-f*l*p+r*x*p+h*l*g-r*d*g,T=h*m*c-f*u*c+f*a*p-r*m*p-h*a*g+r*u*g,S=f*u*l-h*m*l-f*a*d+r*m*d+h*a*x-r*u*x,C=t*_+s*b+i*T+n*S;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/C;return e[0]=_*w,e[1]=(m*d*n-u*x*n-m*i*p+s*x*p+u*i*g-s*d*g)*w,e[2]=(a*x*n-m*l*n+m*i*c-s*x*c-a*i*g+s*l*g)*w,e[3]=(u*l*n-a*d*n-u*i*c+s*d*c+a*i*p-s*l*p)*w,e[4]=b*w,e[5]=(h*x*n-f*d*n+f*i*p-t*x*p-h*i*g+t*d*g)*w,e[6]=(f*l*n-r*x*n-f*i*c+t*x*c+r*i*g-t*l*g)*w,e[7]=(r*d*n-h*l*n+h*i*c-t*d*c-r*i*p+t*l*p)*w,e[8]=T*w,e[9]=(f*u*n-h*m*n-f*s*p+t*m*p+h*s*g-t*u*g)*w,e[10]=(r*m*n-f*a*n+f*s*c-t*m*c-r*s*g+t*a*g)*w,e[11]=(h*a*n-r*u*n-h*s*c+t*u*c+r*s*p-t*a*p)*w,e[12]=S*w,e[13]=(h*m*i-f*u*i+f*s*d-t*m*d-h*s*x+t*u*x)*w,e[14]=(f*a*i-r*m*i-f*s*l+t*m*l+r*s*x-t*a*x)*w,e[15]=(r*u*i-h*a*i+h*s*l-t*u*l-r*s*d+t*a*d)*w,this}scale(e){const t=this.elements,s=e.x,i=e.y,n=e.z;return t[0]*=s,t[4]*=i,t[8]*=n,t[1]*=s,t[5]*=i,t[9]*=n,t[2]*=s,t[6]*=i,t[10]*=n,t[3]*=s,t[7]*=i,t[11]*=n,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){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,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),n=1-s,r=e.x,a=e.y,l=e.z,c=n*r,h=n*a;return this.set(c*r+s,c*a-i*l,c*l+i*a,0,c*a+i*l,h*a+s,h*l-i*r,0,c*l-i*a,h*l+i*r,n*l*l+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,n,r){return this.set(1,s,n,0,e,1,r,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,n=t._x,r=t._y,a=t._z,l=t._w,c=n+n,h=r+r,u=a+a,d=n*c,p=n*h,f=n*u,m=r*h,x=r*u,g=a*u,_=l*c,b=l*h,T=l*u,S=s.x,C=s.y,w=s.z;return i[0]=(1-(m+g))*S,i[1]=(p+T)*S,i[2]=(f-b)*S,i[3]=0,i[4]=(p-T)*C,i[5]=(1-(d+g))*C,i[6]=(x+_)*C,i[7]=0,i[8]=(f+b)*w,i[9]=(x-_)*w,i[10]=(1-(d+m))*w,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;let n=wn.set(i[0],i[1],i[2]).length();const r=wn.set(i[4],i[5],i[6]).length(),a=wn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(n=-n),e.x=i[12],e.y=i[13],e.z=i[14],ps.copy(this);const c=1/n,h=1/r,u=1/a;return ps.elements[0]*=c,ps.elements[1]*=c,ps.elements[2]*=c,ps.elements[4]*=h,ps.elements[5]*=h,ps.elements[6]*=h,ps.elements[8]*=u,ps.elements[9]*=u,ps.elements[10]*=u,t.setFromRotationMatrix(ps),s.x=n,s.y=r,s.z=a,this}makePerspective(e,t,s,i,n,r,a=Ut){const l=this.elements,c=2*n/(t-e),h=2*n/(s-i),u=(t+e)/(t-e),d=(s+i)/(s-i);let p,f;if(a===Ut)p=-(r+n)/(r-n),f=-2*r*n/(r-n);else if(a===Oi)p=-r/(r-n),f=-r*n/(r-n);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,i,n,r,a=Ut){const l=this.elements,c=1/(t-e),h=1/(s-i),u=1/(r-n),d=(t+e)*c,p=(s+i)*h;let f,m;if(a===Ut)f=(r+n)*u,m=-2*u;else if(a===Oi)f=n*u,m=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=m,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<16;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const wn=new N,ps=new Ie,ob=new N(0,0,0),ab=new N(1,1,1),pi=new N,Uo=new N,Wt=new N;class he{constructor(e=0,t=0){he.prototype.isVector2=!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 new 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 new 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){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(pe(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,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){const s=Math.cos(t),i=Math.sin(t),n=this.x-e.x,r=this.y-e.y;return this.x=n*s-r*i+e.x,this.y=n*i+r*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ge{constructor(e=0,t=0,s=0,i=1){ge.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}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,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,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 new 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 new 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?e.w:1,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){const t=this.x,s=this.y,i=this.z,n=this.w,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i+r[12]*n,this.y=r[1]*t+r[5]*s+r[9]*i+r[13]*n,this.z=r[2]*t+r[6]*s+r[10]*i+r[14]*n,this.w=r[3]*t+r[7]*s+r[11]*i+r[15]*n,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);const 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,s,i,n;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],f=l[9],m=l[2],x=l[6],g=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(f-x)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(f+x)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const b=(c+1)/2,T=(p+1)/2,S=(g+1)/2,C=(h+d)/4,w=(u+m)/4,R=(f+x)/4;return b>T&&b>S?b<.01?(s=0,i=.707106781,n=.707106781):(s=Math.sqrt(b),i=C/s,n=w/s):T>S?T<.01?(s=.707106781,i=0,n=.707106781):(i=Math.sqrt(T),s=C/i,n=R/i):S<.01?(s=.707106781,i=.707106781,n=0):(n=Math.sqrt(S),s=w/n,i=R/n),this.set(s,i,n,t),this}let _=Math.sqrt((x-f)*(x-f)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(x-f)/_,this.y=(u-m)/_,this.z=(d-h)/_,this.w=Math.acos((c+p+g-1)/2),this}setFromMatrixPosition(e){const 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=pe(this.x,e.x,t.x),this.y=pe(this.y,e.y,t.y),this.z=pe(this.z,e.z,t.z),this.w=pe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=pe(this.x,e,t),this.y=pe(this.y,e,t),this.z=pe(this.z,e,t),this.w=pe(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(pe(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,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}}function bo(o,e=0){let t=3735928559^e,s=1103547991^e;if(o instanceof Array)for(let i=0,n;i<o.length;i++)n=o[i],t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);else for(let i=0,n;i<o.length;i++)n=o.charCodeAt(i),t=Math.imul(t^n,2654435761),s=Math.imul(s^n,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&s)+(t>>>0)}const lb=o=>bo(o),hu=o=>bo(o),el=(...o)=>bo(o);function Xm(o,e=!1){const t=[];o.isNode===!0&&(t.push(o.id),o=o.getSelf());for(const{property:s,childNode:i}of tl(o))t.push(bo(s.slice(0,-4)),i.getCacheKey(e));return bo(t)}function*tl(o,e=!1){for(const t in o){if(t.startsWith("_")===!0)continue;const s=o[t];if(Array.isArray(s)===!0)for(let i=0;i<s.length;i++){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}else if(s&&s.isNode===!0)yield{property:t,childNode:s};else if(typeof s=="object")for(const i in s){const n=s[i];n&&(n.isNode===!0||e&&typeof n.toJSON=="function")&&(yield{property:t,index:i,childNode:n})}}}const cb=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Vd=new WeakMap;function hb(o){return cb.get(o)}function sl(o){if(o==null)return null;const e=typeof o;return o.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":o.isVector2===!0?"vec2":o.isVector3===!0?"vec3":o.isVector4===!0?"vec4":o.isMatrix2===!0?"mat2":o.isMatrix3===!0?"mat3":o.isMatrix4===!0?"mat4":o.isColor===!0?"color":o instanceof ArrayBuffer?"ArrayBuffer":null}function Zm(o,...e){const t=o?o.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),o==="color"?new ve(...e):t==="vec2"?new he(...e):t==="vec3"?new N(...e):t==="vec4"?new ge(...e):t==="mat2"?new fl(...e):t==="mat3"?new Ht(...e):t==="mat4"?new Ie(...e):o==="bool"?e[0]||!1:o==="float"||o==="int"||o==="uint"?e[0]||0:o==="string"?e[0]||"":o==="ArrayBuffer"?db(e[0]):null}function Km(o){let e=Vd.get(o);return e===void 0&&(e={},Vd.set(o,e)),e}function ub(o){let e="";const t=new Uint8Array(o);for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return btoa(e)}function db(o){return Uint8Array.from(atob(o),e=>e.charCodeAt(0)).buffer}let pb=0;function fb(o){const e=Object.keys(o);let t=Object.getPrototypeOf(o);for(;t;){const s=Object.getOwnPropertyDescriptors(t);for(const i in s)if(s[i]!==void 0){const n=s[i];n&&typeof n.get=="function"&&e.push(i)}t=Object.getPrototypeOf(t)}return e}class mb{constructor(e,t,s,i,n,r,a,l,c,h){this.id=pb++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=n,this.scene=r,this.camera=a,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=n.version,this.drawRange=null,this.attributes=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=h,this.clippingContextCacheKey=h!==null?h.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.material.hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const n of e){const r=n.node&&n.node.attribute?n.node.attribute:t.getAttribute(n.name);if(r===void 0)continue;s.push(r);const a=r.isInterleavedBufferAttribute?r.data:r;i.add(a)}return this.attributes=s,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:n}=this,r=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),l=a!==null;let c=1;if(s.isInstancedBufferGeometry===!0?c=s.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(r.instanceCount=c,e.isBatchedMesh===!0)return r;let h=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(h=2);let u=n.start*h,d=(n.start+n.count)*h;i!==null&&(u=Math.max(u,i.start*h),d=Math.min(d,(i.start+i.count)*h));const p=s.attributes.position;let f=1/0;l?f=a.count:p!=null&&(f=p.count),u=Math.max(u,0),d=Math.min(d,f);const m=d-u;return m<0||m===1/0?null:(r.vertexCount=m,r.firstVertex=u,r)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let n=0,r=i.length;n<r;n++){const a=i[n];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let s=t.customProgramCacheKey();for(const i of fb(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(i))continue;const n=t[i];let r;if(n!==null){const a=typeof n;a==="number"?r=n!==0?"1":"0":a==="object"?(r="{",n.isTexture&&(r+=n.mapping),r+="}"):r=String(n)}else r=String(n);s+=r+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",lb(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=el(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=el(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const Gi=[];class gb{constructor(e,t,s,i,n,r){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=n,this.info=r,this.chainMaps={}}get(e,t,s,i,n,r,a,l){const c=this.getChainMap(l);Gi[0]=e,Gi[1]=t,Gi[2]=r,Gi[3]=n;let h=c.get(Gi);return h===void 0?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,n,r,a,l),c.set(Gi,h)):(h.updateClipping(a),h.needsGeometryUpdate&&h.setGeometry(e.geometry),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,n,r,a,l)):h.version=t.version)),Gi.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,n,r,a,l,c,h,u){const d=this.getChainMap(u),p=new mb(e,t,s,i,n,r,a,l,c,h);return p.onDispose=()=>{this.pipelines.delete(p),this.bindings.delete(p),this.nodes.delete(p),d.delete(p.getChainArray())},p}}class Li{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const as={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},Ci=16,yb=211,xb=212;class _b extends Li{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return t!==null&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(s.version===void 0)t===as.VERTEX?this.backend.createAttribute(e):t===as.INDEX?this.backend.createIndexAttribute(e):t===as.STORAGE?this.backend.createStorageAttribute(e):t===as.INDIRECT&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(s.version<i.version||i.usage===qn)&&(this.backend.updateAttribute(e),s.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const Ys=bb();function bb(){const o=new ArrayBuffer(4),e=new Float32Array(o),t=new Uint32Array(o),s=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(s[l]=0,s[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(s[l]=1024>>-c-14,s[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(s[l]=c+15<<10,s[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(s[l]=31744,s[l|256]=64512,i[l]=24,i[l|256]=24):(s[l]=31744,s[l|256]=64512,i[l]=13,i[l|256]=13)}const n=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,n[l]=c|h}for(let l=1024;l<2048;++l)n[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)r[l]=l<<23;r[31]=1199570944,r[32]=2147483648;for(let l=33;l<63;++l)r[l]=2147483648+(l-32<<23);r[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(a[l]=1024);return{floatView:e,uint32View:t,baseTable:s,shiftTable:i,mantissaTable:n,exponentTable:r,offsetTable:a}}function $t(o){Math.abs(o)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),o=pe(o,-65504,65504),Ys.floatView[0]=o;const e=Ys.uint32View[0],t=e>>23&511;return Ys.baseTable[t]+((e&8388607)>>Ys.shiftTable[t])}function ko(o){const e=o>>10;return Ys.uint32View[0]=Ys.mantissaTable[Ys.offsetTable[e]+(o&1023)]+Ys.exponentTable[e],Ys.floatView[0]}const Qe=new N,zo=new he;let Tb=0;class ls{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Tb++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=Ja,this.updateRanges=[],this.gpuType=Kt,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,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,n=this.itemSize;i<n;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,s=this.count;t<s;t++)zo.fromBufferAttribute(this,t),zo.applyMatrix3(e),this.setXY(t,zo.x,zo.y);else if(this.itemSize===3)for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyMatrix3(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyMatrix4(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.applyNormalMatrix(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Qe.fromBufferAttribute(this,t),Qe.transformDirection(e),this.setXYZ(t,Qe.x,Qe.y,Qe.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=ae(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=n,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const 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!==Ja&&(e.usage=this.usage),e}}class Qm extends ls{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Jm extends ls{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class eg extends ls{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=ko(this.array[e*this.itemSize]);return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize]=$t(t),this}getY(e){let t=ko(this.array[e*this.itemSize+1]);return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+1]=$t(t),this}getZ(e){let t=ko(this.array[e*this.itemSize+2]);return this.normalized&&(t=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+2]=$t(t),this}getW(e){let t=ko(this.array[e*this.itemSize+3]);return this.normalized&&(t=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=ae(t,this.array)),this.array[e*this.itemSize+3]=$t(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this.array[e+2]=$t(i),this}setXYZW(e,t,s,i,n){return e*=this.itemSize,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.array[e+0]=$t(t),this.array[e+1]=$t(s),this.array[e+2]=$t(i),this.array[e+3]=$t(n),this}}class Pt extends ls{constructor(e,t,s){super(new Float32Array(e),t,s)}}function tg(o){return o.index!==null?o.index.version:o.attributes.position.version}function Hd(o){const e=[],t=o.index,s=o.attributes.position;if(t!==null){const n=t.array;for(let r=0,a=n.length;r<a;r+=3){const l=n[r+0],c=n[r+1],h=n[r+2];e.push(l,c,c,h,h,l)}}else{const n=s.array;for(let r=0,a=n.length/3-1;r<a;r+=3){const l=r+0,c=r+1,h=r+2;e.push(l,c,c,h,h,l)}}const i=new(qm(e)?Jm:Qm)(e,1);return i.version=tg(o),i}class Sb extends Li{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,s=this.get(t);s.initialized=!0,this.info.memory.geometries++;const i=()=>{this.info.memory.geometries--;const n=t.index,r=e.getAttributes();n!==null&&this.attributes.delete(n);for(const l of r)this.attributes.delete(l);const a=this.wireframes.get(t);a!==void 0&&this.attributes.delete(a),t.removeEventListener("dispose",i)};t.addEventListener("dispose",i)}updateAttributes(e){const t=e.getAttributes();for(const n of t)n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute?this.updateAttribute(n,as.STORAGE):this.updateAttribute(n,as.VERTEX);const s=this.getIndex(e);s!==null&&this.updateAttribute(s,as.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,as.INDIRECT)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(s.wireframe===!0){const n=this.wireframes;let r=n.get(t);r===void 0?(r=Hd(t),n.set(t,r)):r.version!==tg(t)&&(this.attributes.delete(r),r=Hd(t),n.set(t,r)),i=r}return i}}class vb{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class sg{constructor(e){this.cacheKey=e,this.usedTimes=0}}class wb extends sg{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Mb extends sg{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Cb=0;class Yl{constructor(e,t,s,i=null,n=null){this.id=Cb++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=n,this.usedTimes=0}}class Eb extends Li{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.computeProgram.usedTimes--);const r=this.nodes.getForCompute(e);let a=this.programs.compute.get(r.computeShader);a===void 0&&(n&&n.computeProgram.usedTimes===0&&this._releaseProgram(n.computeProgram),a=new Yl(r.computeShader,"compute",e.name,r.transforms,r.nodeAttributes),this.programs.compute.set(r.computeShader,a),s.createProgram(a));const l=this._getComputeCacheKey(e,a);let c=this.caches.get(l);c===void 0&&(n&&n.usedTimes===0&&this._releasePipeline(n),c=this._getComputePipeline(e,a,l,t)),c.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=c}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const n=i.pipeline;n&&(n.usedTimes--,n.vertexProgram.usedTimes--,n.fragmentProgram.usedTimes--);const r=e.getNodeBuilderState(),a=e.material?e.material.name:"";let l=this.programs.vertex.get(r.vertexShader);l===void 0&&(n&&n.vertexProgram.usedTimes===0&&this._releaseProgram(n.vertexProgram),l=new Yl(r.vertexShader,"vertex",a),this.programs.vertex.set(r.vertexShader,l),s.createProgram(l));let c=this.programs.fragment.get(r.fragmentShader);c===void 0&&(n&&n.fragmentProgram.usedTimes===0&&this._releaseProgram(n.fragmentProgram),c=new Yl(r.fragmentShader,"fragment",a),this.programs.fragment.set(r.fragmentShader,c),s.createProgram(c));const h=this._getRenderCacheKey(e,l,c);let u=this.caches.get(h);u===void 0?(n&&n.usedTimes===0&&this._releasePipeline(n),u=this._getRenderPipeline(e,l,c,h,t)):e.pipeline=u,u.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=u}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let n=this.caches.get(s);return n===void 0&&(n=new Mb(s,t),this.caches.set(s,n),this.backend.createComputePipeline(n,i)),n}_getRenderPipeline(e,t,s,i,n){i=i||this._getRenderCacheKey(e,t,s);let r=this.caches.get(i);return r===void 0&&(r=new wb(i,t,s),this.caches.set(i,r),e.pipeline=r,this.backend.createRenderPipeline(e,n)),r}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class Ab extends Li{constructor(e,t,s,i,n,r){super(),this.backend=e,this.textures=s,this.pipelines=n,this.attributes=i,this.nodes=t,this.info=r,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const s of t){const i=this.get(s);i.bindGroup===void 0&&(this._init(s),this.backend.createBindings(s,t,0),i.bindGroup=s)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const s=t.attribute,i=s.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(s,i)}}_update(e,t){const{backend:s}=this;let i=!1,n=!0,r=0,a=0;for(const l of e.bindings)if(!(l.isNodeUniformsGroup&&this.nodes.updateGroup(l)===!1)){if(l.isStorageBuffer){const c=l.attribute,h=c.isIndirectStorageBufferAttribute?as.INDIRECT:as.STORAGE;this.attributes.update(c,h)}if(l.isUniformBuffer)l.update()&&s.updateBinding(l);else if(l.isSampler)l.update();else if(l.isSampledTexture){const c=this.textures.get(l.texture);l.needsBindingsUpdate(c.generation)&&(i=!0);const h=l.update(),u=l.texture;h&&this.textures.updateTexture(u);const d=s.get(u);if(d.externalTexture!==void 0||c.isDefaultTexture?n=!1:(r=r*10+u.id,a+=u.version),s.isWebGPUBackend===!0&&d.texture===void 0&&d.externalTexture===void 0&&(console.error("Bindings._update: binding should be available:",l,h,u,l.textureNode.value,i),this.textures.updateTexture(u),i=!0),u.isStorageTexture===!0){const p=this.get(u);l.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(u)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(u),p.needsMipmap=!1)}}}i===!0&&this.backend.updateBindings(e,t,n?r:0,a)}}function Rb(o,e){return o.groupOrder!==e.groupOrder?o.groupOrder-e.groupOrder:o.renderOrder!==e.renderOrder?o.renderOrder-e.renderOrder:o.z!==e.z?o.z-e.z:o.id-e.id}function Wd(o,e){return o.groupOrder!==e.groupOrder?o.groupOrder-e.groupOrder:o.renderOrder!==e.renderOrder?o.renderOrder-e.renderOrder:o.z!==e.z?e.z-o.z:o.id-e.id}function $d(o){return(o.transmission>0||o.transmissionNode)&&o.side===Jn&&o.forceSinglePass===!1}class Nb{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,n,r,a){let l=this.renderItems[this.renderItemsIndex];return l===void 0?(l={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:n,group:r,clippingContext:a},this.renderItems[this.renderItemsIndex]=l):(l.id=e.id,l.object=e,l.geometry=t,l.material=s,l.groupOrder=i,l.renderOrder=e.renderOrder,l.z=n,l.group=r,l.clippingContext=a),this.renderItemsIndex++,l}push(e,t,s,i,n,r,a){const l=this.getNextRenderItem(e,t,s,i,n,r,a);e.occlusionTest===!0&&this.occlusionQueryCount++,s.transparent===!0||s.transmission>0?($d(s)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,s,i,n,r,a){const l=this.getNextRenderItem(e,t,s,i,n,r,a);s.transparent===!0||s.transmission>0?($d(s)&&this.transparentDoublePass.unshift(l),this.transparent.unshift(l)):this.opaque.unshift(l)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Rb),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Wd),this.transparent.length>1&&this.transparent.sort(t||Wd)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const s=this.renderItems[e];if(s.id===null)break;s.id=null,s.object=null,s.geometry=null,s.material=null,s.groupOrder=null,s.renderOrder=null,s.z=null,s.group=null,s.clippingContext=null}}}const Er=[];class Pb{constructor(e){this.lighting=e,this.lists=new vs}get(e,t){const s=this.lists;Er[0]=e,Er[1]=t;let i=s.get(Er);return i===void 0&&(i=new Nb(this.lighting,e,t),s.set(Er,i)),Er.length=0,i}dispose(){this.lists=new vs}}let Fb=0;class Db{constructor(){this.id=Fb++,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new ge,this.scissor=!1,this.scissorValue=new ge,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return ig(this)}}function ig(o){const{textures:e,activeCubeFace:t}=o,s=[t];for(const i of e)s.push(i.id);return hu(s)}let pn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,r=i.length;n<r;n++)i[n].call(this,e);e.target=null}}};const jd=new Ie,qd=new xr;class us{constructor(e=0,t=0,s=0,i=us.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,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,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,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,s=!0){const i=e.elements,n=i[0],r=i[4],a=i[8],l=i[1],c=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(pe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-pe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,n),this._z=0);break;case"ZXY":this._x=Math.asin(pe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(l,n));break;case"ZYX":this._y=Math.asin(-pe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,n)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(pe(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,n)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-pe(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return jd.makeRotationFromQuaternion(e),this.setFromRotationMatrix(jd,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return qd.setFromEuler(this),this.setFromQuaternion(qd,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}}us.DEFAULT_ORDER="XYZ";class Ob{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}}let Bb=0;const Yd=new N,Mn=new xr,Vs=new Ie,Go=new N,Ar=new N,Ib=new N,Lb=new xr,Xd=new N(1,0,0),Zd=new N(0,1,0),Kd=new N(0,0,1),Qd={type:"added"},Ub={type:"removed"},Cn={type:"childadded",child:null},Xl={type:"childremoved",child:null};class dt extends pn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Bb++}),this.uuid=Ks(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=dt.DEFAULT_UP.clone();const e=new N,t=new us,s=new xr,i=new N(1,1,1);function n(){s.setFromEuler(t,!1)}function r(){t.setFromQuaternion(s,void 0,!1)}t._onChange(n),s._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ie},normalMatrix:{value:new Ht}}),this.matrix=new Ie,this.matrixWorld=new Ie,this.matrixAutoUpdate=dt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ob,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.userData={}}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 Mn.setFromAxisAngle(e,t),this.quaternion.multiply(Mn),this}rotateOnWorldAxis(e,t){return Mn.setFromAxisAngle(e,t),this.quaternion.premultiply(Mn),this}rotateX(e){return this.rotateOnAxis(Xd,e)}rotateY(e){return this.rotateOnAxis(Zd,e)}rotateZ(e){return this.rotateOnAxis(Kd,e)}translateOnAxis(e,t){return Yd.copy(e).applyQuaternion(this.quaternion),this.position.add(Yd.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Xd,e)}translateY(e){return this.translateOnAxis(Zd,e)}translateZ(e){return this.translateOnAxis(Kd,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Vs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Go.copy(e):Go.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Ar.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Vs.lookAt(Ar,Go,this.up):Vs.lookAt(Go,Ar,this.up),this.quaternion.setFromRotationMatrix(Vs),i&&(Vs.extractRotation(i.matrixWorld),Mn.setFromRotationMatrix(Vs),this.quaternion.premultiply(Mn.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.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(Qd),Cn.child=e,this.dispatchEvent(Cn),Cn.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.remove(arguments[s]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Ub),Xl.child=e,this.dispatchEvent(Xl),Xl.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Vs.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Vs.multiply(e.parent.matrixWorld)),e.applyMatrix4(Vs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Qd),Cn.child=e,this.dispatchEvent(Cn),Cn.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 s=0,i=this.children.length;s<i;s++){const r=this.children[s].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let n=0,r=i.length;n<r;n++)i[n].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ar,e,Ib),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ar,Lb,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),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);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}updateWorldMatrix(e,t){const s=this.parent;if(e===!0&&s!==null&&s.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){const i=this.children;for(let n=0,r=i.length;n<r;n++)i[n].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function n(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=n(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];n(e.shapes,u)}else n(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(n(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let l=0,c=this.material.length;l<c;l++)a.push(n(e.materials,this.material[l]));i.material=a}else i.material=n(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){const l=this.animations[a];i.animations.push(n(e.animations,l))}}if(t){const a=r(e.geometries),l=r(e.materials),c=r(e.textures),h=r(e.images),u=r(e.shapes),d=r(e.skeletons),p=r(e.animations),f=r(e.nodes);a.length>0&&(s.geometries=a),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),h.length>0&&(s.images=h),u.length>0&&(s.shapes=u),d.length>0&&(s.skeletons=d),p.length>0&&(s.animations=p),f.length>0&&(s.nodes=f)}return s.object=i,s;function r(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}}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.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.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let s=0;s<e.children.length;s++){const i=e.children[s];this.add(i.clone())}return this}}dt.DEFAULT_UP=new N(0,1,0);dt.DEFAULT_MATRIX_AUTO_UPDATE=!0;dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class uu extends dt{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 us,this.environmentIntensity=1,this.environmentRotation=new us,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){const 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}}class du extends dt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ie,this.projectionMatrix=new Ie,this.projectionMatrixInverse=new Ie,this.coordinateSystem=Ut}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Rr=[],kb=new uu,zb=new du;class Gb{constructor(){this.chainMaps={}}get(e,t,s=null){Rr[0]=e,Rr[1]=t;let i;if(s===null)i="default";else{const a=s.texture.format;i=`${s.textures.length}:${a}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this._getChainMap(i);let r=n.get(Rr);return r===void 0&&(r=new Db,n.set(Rr,r)),Rr.length=0,s!==null&&(r.sampleCount=s.samples===0?1:s.samples),r}getForClear(e=null){return this.get(kb,zb,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new vs)}dispose(){this.chainMaps={}}}let En;class Vb{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{En===void 0&&(En=Bh("canvas")),En.width=e.width,En.height=e.height;const i=En.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),s=En}return s.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Bh("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),n=i.data;for(let r=0;r<n.length;r++)n[r]=si(n[r]/255)*255;return s.putImageData(i,0,0),t}else if(e.data){const t=e.data.slice(0);for(let s=0;s<t.length;s++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[s]=Math.floor(si(t[s]/255)*255):t[s]=si(t[s]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Hb=0;class pu{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Hb++}),this.uuid=Ks(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(i!==null){let n;if(Array.isArray(i)){n=[];for(let r=0,a=i.length;r<a;r++)i[r].isDataTexture?n.push(Zl(i[r].image)):n.push(Zl(i[r]))}else n=Zl(i);s.url=n}return t||(e.images[this.uuid]=s),s}}function Zl(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?Vb.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let Wb=0;const Kl=new N;class St extends pn{constructor(e=St.DEFAULT_IMAGE,t=St.DEFAULT_MAPPING,s=Ri,i=Ri,n=Qt,r=ei,a=os,l=Nt,c=St.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Wb++}),this.uuid=Ks(),this.name="",this.source=new pu(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=n,this.minFilter=r,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=l,this.offset=new he(0,0),this.repeat=new he(1,1),this.center=new he(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ht,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Kl).x}get height(){return this.source.getSize(Kl).y}get depth(){return this.source.getSize(Kl).z}get image(){return this.source.data}set image(e=null){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.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(const t in e){const s=e[t];if(s===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const s={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,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&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==tu)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ur:e.x=e.x-Math.floor(e.x);break;case Ri:e.x=e.x<0?0:1;break;case dr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ur:e.y=e.y-Math.floor(e.y);break;case Ri:e.y=e.y<0?0:1;break;case dr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-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++}}St.DEFAULT_IMAGE=null;St.DEFAULT_MAPPING=tu;St.DEFAULT_ANISOTROPY=1;class Is extends St{constructor(e,t,s=Xe,i,n,r,a=ut,l=ut,c,h=Bs,u=1){if(h!==Bs&&h!==ti)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:u};super(d,i,n,r,a,l,h,s,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new pu(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const $b=new N;class jb extends Li{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=e.samples===0?1:e.samples,n=s.depthTextureMips||(s.depthTextureMips={}),r=e.textures,a=this.getSize(r[0]),l=a.width>>t,c=a.height>>t;let h=e.depthTexture||n[t];const u=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;h===void 0&&u&&(h=new Is,h.format=e.stencilBuffer?ti:Bs,h.type=e.stencilBuffer?Fi:Xe,h.image.width=l,h.image.height=c,h.image.depth=a.depth,h.isArrayTexture=e.multiview===!0&&a.depth>1,n[t]=h),(s.width!==a.width||a.height!==s.height)&&(d=!0,h&&(h.needsUpdate=!0,h.image.width=l,h.image.height=c,h.image.depth=h.isArrayTexture?h.image.depth:1)),s.width=a.width,s.height=a.height,s.textures=r,s.depthTexture=h||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(d=!0,h&&(h.needsUpdate=!0),s.sampleCount=i);const p={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let f=0;f<r.length;f++){const m=r[f];d&&(m.needsUpdate=!0),this.updateTexture(m,p)}h&&this.updateTexture(h,p)}if(s.initialized!==!0){s.initialized=!0;const f=()=>{e.removeEventListener("dispose",f);for(let m=0;m<r.length;m++)this._destroyTexture(r[m]);h&&this._destroyTexture(h),this.delete(e)};e.addEventListener("dispose",f)}}updateTexture(e,t={}){const s=this.get(e);if(s.initialized===!0&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,n=this.backend;if(i&&s.initialized===!0&&(n.destroySampler(e),n.destroyTexture(e)),e.isFramebufferTexture){const c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=Nt}const{width:r,height:a,depth:l}=this.getSize(e);if(t.width=r,t.height=a,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,r,a):1,i||e.isStorageTexture===!0)n.createSampler(e),n.createTexture(e,t),s.generation=e.version;else if(s.initialized!==!0&&n.createSampler(e),e.version>0){const h=e.image;if(h===void 0)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(h.complete===!1)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const u=[];for(const d of e.images)u.push(d);t.images=u}else t.image=h;(s.isDefaultTexture===void 0||s.isDefaultTexture===!0)&&(n.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),e.source.dataReady===!0&&n.updateTexture(e,t),t.needsMipmaps&&e.mipmaps.length===0&&n.generateMipmaps(e)}}else n.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;if(s.initialized!==!0){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const c=()=>{e.removeEventListener("dispose",c),this._destroyTexture(e)};e.addEventListener("dispose",c)}s.version=e.version}getSize(e,t=$b){let s=e.images?e.images[0]:e.image;return s?(s.image!==void 0&&(s=s.image),t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return e.isCompressedTexture?e.mipmaps?i=e.mipmaps.length:i=1:i=Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return e.isCompressedTexture===!0||e.generateMipmaps}_destroyTexture(e){this.has(e)===!0&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class fu extends ve{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}const Vo={VERTEX:"vertex"},ue={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Zs={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},qb=["fragment","vertex"],Jd=["setup","analyze","generate"],ep=[...qb,"compute"],_r=["x","y","z","w"],Yb={analyze:"setup",generate:"analyze"};let Xb=0;class re extends pn{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ue.NONE,this.updateBeforeType=ue.NONE,this.updateAfterType=ue.NONE,this.uuid=s_.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Xb++})}set needsUpdate(e){e===!0&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,ue.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ue.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ue.OBJECT)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of tl(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return e=e||this.version!==this._cacheKeyVersion,(e===!0||this._cacheKey===null)&&(this._cacheKey=el(Xm(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())t["node"+s++]=i;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(this.parents===!0){const i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(s===1){const i=e.getNodeProperties(this);for(const n of Object.values(i))n&&n.isNode===!0&&n.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&s.isNode===!0)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const n=Yb[e.buildStage];if(n&&i.buildStages[n]!==!0){const l=e.getBuildStage();e.setBuildStage(n),this.build(e),e.setBuildStage(l)}e.addNode(this),e.addChain(this);let r=null;const a=e.getBuildStage();if(a==="setup"){this.updateReference(e);const l=e.getNodeProperties(this);if(l.initialized!==!0){l.initialized=!0,l.outputNode=this.setup(e)||l.outputNode||null;for(const c of Object.values(l))if(c&&c.isNode===!0){if(c.parents===!0){const h=e.getNodeProperties(c);h.parents=h.parents||[],h.parents.push(this)}c.build(e)}}r=l.outputNode}else if(a==="analyze")this.analyze(e,t);else if(a==="generate")if(this.generate.length===1){const c=this.getNodeType(e),h=e.getDataFromNode(this);r=h.snippet,r===void 0?h.generated===void 0?(h.generated=!0,r=this.generate(e)||"",h.snippet=r):(console.warn("THREE.Node: Recursion detected.",this),r=""):h.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),r=e.format(r,c,t)}else r=this.generate(e,t)||"";return e.removeChain(this),e.addSequentialNode(this),r}getSerializeChildren(){return tl(this)}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:n,childNode:r}of t)n!==void 0?(s[i]===void 0&&(s[i]=Number.isInteger(n)?[]:{}),s[i][n]=r.toJSON(e.meta).uuid):s[i]=r.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const n of e.inputNodes[s])i.push(t[n]);this[s]=i}else if(typeof e.inputNodes[s]=="object"){const i={};for(const n in e.inputNodes[s]){const r=e.inputNodes[s][n];i[n]=t[r]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let n=e.nodes[t];n===void 0&&(n={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[n.uuid]=n),this.serialize(n),delete n.meta);function r(a){const l=[];for(const c in a){const h=a[c];delete h.metadata,l.push(h)}return l}if(i){const a=r(e.textures),l=r(e.images),c=r(e.nodes);a.length>0&&(n.textures=a),l.length>0&&(n.images=l),c.length>0&&(n.nodes=c)}return n}}class nt extends re{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){const i=e.getVectorType(this.getNodeType(e,t)),n=e.getDataFromNode(this);if(n.propertyName!==void 0)return e.format(n.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){const r=super.build(e,i),a=e.getVarFromNode(this,null,i),l=e.getPropertyName(a);return e.addLineFlowCode(`${l} = ${r}`,this),n.snippet=r,n.propertyName=l,e.format(n.propertyName,i,t)}}return super.build(e,t)}}class Co extends re{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e),s=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${s}[ ${i} ]`}}class ng extends re{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))(s===null||e.getTypeLength(t)===e.getTypeLength(i))&&(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),n=s.build(e,i);return e.format(n,i,t)}}class Zb extends nt{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),n=this.nodes,r=e.getComponentType(s),a=[];let l=0;for(const h of n){if(l>=i){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let u=h.getNodeType(e),d=e.getTypeLength(u),p;l+d>i&&(console.error(`THREE.TSL: Length of '${s}()' data exceeds maximum length of output type.`),d=i-l,u=e.getTypeFromLength(d)),l+=d,p=h.build(e,u);const f=e.getComponentType(u);f!==r&&(p=e.format(p,f,r)),a.push(p)}const c=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(c,s,t)}}const Kb=_r.join("");class tp extends re{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(_r.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let n=null;if(i>1){let r=null;this.getVectorLength()>=i&&(r=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const l=s.build(e,r);this.components.length===i&&this.components===Kb.slice(0,this.components.length)?n=e.format(l,r,t):n=e.format(`${l}.${this.components}`,this.getNodeType(e),t)}else n=s.build(e,t);return n}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Qb extends nt{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,n=this.getNodeType(e),r=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(s.length,r),l=i.build(e,a),c=t.build(e,n),h=e.getTypeLength(n),u=[];for(let d=0;d<h;d++){const p=_r[d];p===s[0]?(u.push(l),d+=s.length-1):u.push(c+"."+p)}return`${e.getType(n)}( ${u.join(", ")} )`}}class Jb extends nt{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),n=s.build(e),r=e.getVarFromNode(this),a=e.getPropertyName(r);e.addLineFlowCode(a+" = "+n,this);const l=e.getTypeLength(i),c=[];let h=0;for(let u=0;u<l;u++){const d=_r[u];d===t[h]?(c.push("1.0 - "+(a+"."+d)),h++):c.push(a+"."+d)}return`${e.getType(i)}( ${c.join(", ")} )`}}class mu extends re{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return this.nodeType===null?sl(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=sl(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=ub(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Zm(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const sp=/float|u?int/;class ci extends mu{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return sp.test(s)&&sp.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class eT extends re{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let pr=null;const Yn=new Map;function O(o,e){if(Yn.has(o)){console.warn(`THREE.TSL: Redefinition of method chaining '${o}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${o} is not a function`);Yn.set(o,e)}const rg=o=>o.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),ip=o=>rg(o).split("").sort().join(""),og={setup(o,e){const t=e.shift();return o(yl(t),...e)},get(o,e,t){if(typeof e=="string"&&o[e]===void 0){if(o.isStackNode!==!0&&e==="assign")return(...s)=>(pr.assign(t,...s),t);if(Yn.has(e)){const s=Yn.get(e);return o.isStackNode?(...i)=>t.add(s(...i)):(...i)=>s(t,...i)}else{if(e==="self")return o;if(e.endsWith("Assign")&&Yn.has(e.slice(0,e.length-6))){const s=Yn.get(e.slice(0,e.length-6));return o.isStackNode?(...i)=>t.assign(i[0],s(...i)):(...i)=>t.assign(s(t,...i))}else{if(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0)return e=rg(e),k(new tp(t,e));if(/^set[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=ip(e.slice(3).toLowerCase()),s=>k(new Qb(o,e,k(s)));if(/^flip[XYZWRGBASTPQ]{1,4}$/.test(e)===!0)return e=ip(e.slice(4).toLowerCase()),()=>k(new Jb(k(o),e));if(e==="width"||e==="height"||e==="depth")return e==="width"?e="x":e==="height"?e="y":e==="depth"&&(e="z"),k(new tp(o,e));if(/^\d+$/.test(e)===!0)return k(new Co(t,new ci(Number(e),"uint")));if(/^get$/.test(e)===!0)return s=>k(new eT(t,s))}}}return Reflect.get(o,e,t)},set(o,e,t,s){return typeof e=="string"&&o[e]===void 0&&(/^[xyzwrgbastpq]{1,4}$/.test(e)===!0||e==="width"||e==="height"||e==="depth"||/^\d+$/.test(e)===!0)?(s[e].assign(t),!0):Reflect.set(o,e,t,s)}},Ql=new WeakMap,np=new WeakMap,tT=function(o,e=null){const t=sl(o);if(t==="node"){let s=Ql.get(o);return s===void 0&&(s=new Proxy(o,og),Ql.set(o,s),Ql.set(s,s)),s}else{if(e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string")return k(Ih(o,e));if(t==="shader")return L(o)}return o},sT=function(o,e=null){for(const t in o)o[t]=k(o[t],e);return o},iT=function(o,e=null){const t=o.length;for(let s=0;s<t;s++)o[s]=k(o[s],e);return o},nT=function(o,e=null,t=null,s=null){const i=h=>k(s!==null?Object.assign(h,s):h);let n,r=e,a,l;function c(h){let u;return r?u=/[a-z]/i.test(r)?r+"()":r:u=o.type,a!==void 0&&h.length<a?(console.error(`THREE.TSL: "${u}" parameter length is less than minimum required.`),h.concat(new Array(a-h.length).fill(0))):l!==void 0&&h.length>l?(console.error(`THREE.TSL: "${u}" parameter length exceeds limit.`),h.slice(0,l)):h}return e===null?n=(...h)=>i(new o(...ir(c(h)))):t!==null?(t=k(t),n=(...h)=>i(new o(e,...ir(c(h)),t))):n=(...h)=>i(new o(e,...ir(c(h)))),n.setParameterLength=(...h)=>(h.length===1?a=l=h[0]:h.length===2&&([a,l]=h),n),n.setName=h=>(r=h,n),n},rT=function(o,...e){return k(new o(...ir(e)))};class oT extends re{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t),n=t.namespace&&t.namespace===e.namespace?e.getNamespace("once"):"once";if(i[n])return i[n];let r=null;if(t.layout){let a=np.get(e.constructor);a===void 0&&(a=new WeakMap,np.set(e.constructor,a));let l=a.get(t);l===void 0&&(l=k(e.buildFunctionNode(t)),a.set(t,l)),e.addInclude(l),r=k(l.call(s))}else{const a=t.jsFunc,l=s!==null||a.length>1?a(s||[],e):a(e);r=k(l)}return t.once&&(i[n]=r),r}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getOutputNamespace();return t[s]=t[s]||this.setupOutput(e),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),n=e.getNodeProperties(this),r=e.getOutputNamespace(),a=this.getOutputNode(e);if(i==="setup"){const l=e.getNamespace("initialized");n[l]!==!0&&(n[l]=!0,n[r]=this.getOutputNode(e),n[r].build(e)),s=n[r]}else i==="analyze"?a.build(e,t):i==="generate"&&(s=a.build(e,t)||"");return s}}class aT extends re{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1,this.namespace=null}setLayout(e){return this.layout=e,this}call(e=null){return yl(e),k(new oT(this,e))}setup(){return this.call()}}const lT=[!1,!0],cT=[0,1,2,3],hT=[-1,-2],ag=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],gu=new Map;for(const o of lT)gu.set(o,new ci(o));const yu=new Map;for(const o of cT)yu.set(o,new ci(o,"uint"));const xu=new Map([...yu].map(o=>new ci(o.value,"int")));for(const o of hT)xu.set(o,new ci(o,"int"));const ml=new Map([...xu].map(o=>new ci(o.value)));for(const o of ag)ml.set(o,new ci(o));for(const o of ag)ml.set(-o,new ci(-o));const gl={bool:gu,uint:yu,ints:xu,float:ml},rp=new Map([...gu,...ml]),Ih=(o,e)=>rp.has(o)?rp.get(o):o.isNode===!0?o:new ci(o,e),uT=o=>{try{return o.getNodeType()}catch{return}},rt=function(o,e=null){return(...t)=>{if((t.length===0||!["bool","float","int","uint"].includes(o)&&t.every(i=>typeof i!="object"))&&(t=[Zm(o,...t)]),t.length===1&&e!==null&&e.has(t[0]))return k(e.get(t[0]));if(t.length===1){const i=Ih(t[0],o);return uT(i)===o?k(i):k(new ng(i,o))}const s=t.map(i=>Ih(i));return k(new Zb(s,o))}},op=o=>typeof o=="object"&&o!==null?o.value:o,dT=o=>o!=null?o.nodeType||o.convertTo||(typeof o=="string"?o:null):null;function eo(o,e){return new Proxy(new aT(o,e),og)}const k=(o,e=null)=>tT(o,e),yl=(o,e=null)=>new sT(o,e),ir=(o,e=null)=>new iT(o,e),U=(...o)=>new nT(...o),V=(...o)=>new rT(...o);let pT=0;const L=(o,e=null)=>{let t=null;e!==null&&(typeof e=="object"?t=e.return:(typeof e=="string"?t=e:console.error("THREE.TSL: Invalid layout type."),e=null));const s=new eo(o,t),i=(...n)=>{let r;yl(n),n[0]&&(n[0].isNode||Object.getPrototypeOf(n[0])!==Object.prototype)?r=[...n]:r=n[0];const l=s.call(r);return t==="void"&&l.toStack(),l};if(i.shaderNode=s,i.id=s.id,i.getNodeType=(...n)=>s.getNodeType(...n),i.getCacheKey=(...n)=>s.getCacheKey(...n),i.setLayout=n=>(s.setLayout(n),i),i.once=(n=null)=>(s.once=!0,s.namespace=n,i),e!==null){if(typeof e.inputs!="object"){const n={name:"fn"+pT++,type:t,inputs:[]};for(const r in e)r!=="return"&&n.inputs.push({name:r,type:e[r]});e=n}i.setLayout(e)}return i},il=o=>{pr=o},lg=()=>pr,Ze=(...o)=>pr.If(...o);function cg(o){return pr&&pr.add(o),o}O("toStack",cg);const fT=new rt("color"),B=new rt("float",gl.float),ke=new rt("int",gl.ints),mT=new rt("uint",gl.uint),_u=new rt("bool",gl.bool),H=new rt("vec2"),qs=new rt("ivec2"),gT=new rt("uvec2"),yT=new rt("bvec2"),I=new rt("vec3"),xT=new rt("ivec3"),_T=new rt("uvec3"),bT=new rt("bvec3"),ne=new rt("vec4"),TT=new rt("ivec4"),ST=new rt("uvec4"),vT=new rt("bvec4"),bu=new rt("mat2"),Ft=new rt("mat3"),nr=new rt("mat4");O("toColor",fT);O("toFloat",B);O("toInt",ke);O("toUint",mT);O("toBool",_u);O("toVec2",H);O("toIVec2",qs);O("toUVec2",gT);O("toBVec2",yT);O("toVec3",I);O("toIVec3",xT);O("toUVec3",_T);O("toBVec3",bT);O("toVec4",ne);O("toIVec4",TT);O("toUVec4",ST);O("toBVec4",vT);O("toMat2",bu);O("toMat3",Ft);O("toMat4",nr);const wT=U(Co).setParameterLength(2),MT=(o,e)=>k(new ng(k(o),e));O("element",wT);O("convert",MT);O("append",o=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),cg(o)));class CT extends nt{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return _r.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=e.getNodeProperties(this);i.sourceNode=s,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),n=this.needsSplitAssign(e),r=s.getNodeType(e),a=s.build(e),l=i.build(e,r),c=i.getNodeType(e),h=e.getDataFromNode(this);let u;if(h.initialized===!0)t!=="void"&&(u=a);else if(n){const d=e.getVarFromNode(this,null,r),p=e.getPropertyName(d);e.addLineFlowCode(`${p} = ${l}`,this);const f=s.node,x=f.node.context({assign:!0}).build(e);for(let g=0;g<f.components.length;g++){const _=f.components[g];e.addLineFlowCode(`${x}.${_} = ${p}[ ${g} ]`,this)}t!=="void"&&(u=a)}else u=`${a} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(u,this),t!=="void"&&(u=a));return h.initialized=!0,e.format(u,r,t)}}const ET=U(CT).setParameterLength(2);O("assign",ET);class ap extends nt{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getNodeType(e){return this.nodeType===null&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const AT=(...o)=>{let e;if(o.length===1){const t=o[0];e=new ap(null,t.length,t)}else{const t=o[0],s=o[1];e=new ap(t,s)}return k(e)};O("toArray",(o,e)=>AT(Array(e).fill(o)));class hg extends re{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const RT=o=>new hg(o),Tu=(o,e=0)=>new hg(o,!0,e),NT=Tu("frame"),K=Tu("render"),ug=RT("object");class Eo extends mu{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=ug}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate(i=>{const n=e(i,s);n!==void 0&&(this.value=n)},t)}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let n=e.getNodeFromHash(i);n===void 0&&(e.setHashNode(this,i),n=this);const r=n.getInputType(e),a=e.getUniformFromNode(n,r,e.shaderStage,this.name||e.context.label),l=e.getPropertyName(a);return e.context.label!==void 0&&delete e.context.label,e.format(l,s,t)}}const Q=(o,e)=>{const t=dT(e||o),s=o&&o.isNode===!0?o.node&&o.node.value||o.value:o;return k(new Eo(s,t))};class Re extends re{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return this.varying===!0?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const dg=(o,e)=>k(new Re(o,e)),nl=(o,e)=>k(new Re(o,e,!0)),Se=V(Re,"vec4","DiffuseColor"),lp=V(Re,"vec3","EmissiveColor"),Xs=V(Re,"float","Roughness"),rl=V(Re,"float","Metalness"),Lh=V(Re,"float","Clearcoat"),ol=V(Re,"float","ClearcoatRoughness"),Xn=V(Re,"vec3","Sheen"),Su=V(Re,"float","SheenRoughness"),vu=V(Re,"float","Iridescence"),pg=V(Re,"float","IridescenceIOR"),fg=V(Re,"float","IridescenceThickness"),Uh=V(Re,"float","AlphaT"),tn=V(Re,"float","Anisotropy"),Oa=V(Re,"vec3","AnisotropyT"),rr=V(Re,"vec3","AnisotropyB"),Yt=V(Re,"color","SpecularColor"),al=V(Re,"float","SpecularF90"),kh=V(Re,"float","Shininess"),uo=V(Re,"vec4","Output"),Jl=V(Re,"float","dashSize"),cp=V(Re,"float","gapSize"),Ba=V(Re,"float","IOR"),zh=V(Re,"float","Transmission"),mg=V(Re,"float","Thickness"),gg=V(Re,"float","AttenuationDistance"),yg=V(Re,"color","AttenuationColor"),xg=V(Re,"float","Dispersion");class PT extends nt{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),n=this.parameters,r=(l,c)=>{const h=c.type,u=h==="pointer";let d;return u?d="&"+l.build(e):d=l.build(e,h),d};if(Array.isArray(n)){if(n.length>i.length)console.error("THREE.TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),n.length=i.length;else if(n.length<i.length)for(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");n.length<i.length;)n.push(B(0));for(let l=0;l<n.length;l++)t.push(r(n[l],i[l]))}else for(const l of i){const c=n[l.name];c!==void 0?t.push(r(c,l)):(console.error(`THREE.TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(r(B(0),l)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const FT=(o,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?ir(e):yl(e[0]),k(new PT(k(o),e)));O("call",FT);const DT={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class We extends nt{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let n=new We(e,t,s);for(let r=0;r<i.length-1;r++)n=new We(e,n,i[r]);t=n,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(DT[this.op],t)}getNodeType(e){const t=this.op,s=this.aNode,i=this.bNode,n=s.getNodeType(e),r=i?i.getNodeType(e):null;if(n==="void"||r==="void")return"void";if(t==="%")return n;if(t==="~"||t==="&"||t==="|"||t==="^"||t===">>"||t==="<<")return e.getIntegerType(n);if(t==="!"||t==="&&"||t==="||"||t==="^^")return"bool";if(t==="=="||t==="!="||t==="<"||t===">"||t==="<="||t===">="){const a=Math.max(e.getTypeLength(n),e.getTypeLength(r));return a>1?`bvec${a}`:"bool"}else{if(e.isMatrix(n)){if(r==="float")return n;if(e.isVector(r))return e.getVectorFromMatrix(n);if(e.isMatrix(r))return n}else if(e.isMatrix(r)){if(n==="float")return r;if(e.isVector(n))return e.getVectorFromMatrix(r)}return e.getTypeLength(r)>e.getTypeLength(n)?r:n}}generate(e,t){const s=this.op,{aNode:i,bNode:n}=this,r=this.getNodeType(e);let a=null,l=null;r!=="void"?(a=i.getNodeType(e),l=n?n.getNodeType(e):null,s==="<"||s===">"||s==="<="||s===">="||s==="=="||s==="!="?e.isVector(a)?l=a:e.isVector(l)?a=l:a!==l&&(a=l="float"):s===">>"||s==="<<"?(a=r,l=e.changeComponentType(l,"uint")):s==="%"?(a=r,l=e.isInteger(a)&&e.isInteger(l)?l:a):e.isMatrix(a)?l==="float"?l="float":e.isVector(l)?l=e.getVectorFromMatrix(a):e.isMatrix(l)||(a=l=r):e.isMatrix(l)?a==="float"?a="float":e.isVector(a)?a=e.getVectorFromMatrix(l):a=l=r:a=l=r):a=l=r;const c=i.build(e,a),h=n?n.build(e,l):null,u=e.getFunctionOperator(s);if(t!=="void"){const d=e.renderer.coordinateSystem===Ut;if(s==="=="||s==="!="||s==="<"||s===">"||s==="<="||s===">=")return d?e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t):e.format(`( ${c} ${s} ${h} )`,r,t);if(s==="%")return e.isInteger(l)?e.format(`( ${c} % ${h} )`,r,t):e.format(`${this.getOperatorMethod(e,r)}( ${c}, ${h} )`,r,t);if(s==="!"||s==="~")return e.format(`(${s}${c})`,a,t);if(u)return e.format(`${u}( ${c}, ${h} )`,r,t);if(e.isMatrix(a)&&l==="float")return e.format(`( ${h} ${s} ${c} )`,r,t);if(a==="float"&&e.isMatrix(l))return e.format(`${c} ${s} ${h}`,r,t);{let p=`( ${c} ${s} ${h} )`;return!d&&r==="bool"&&e.isVector(a)&&e.isVector(l)&&(p=`all${p}`),e.format(p,r,t)}}else if(a!=="void")return u?e.format(`${u}( ${c}, ${h} )`,r,t):e.isMatrix(a)&&l==="float"?e.format(`${h} ${s} ${c}`,r,t):e.format(`${c} ${s} ${h}`,r,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Dt=U(We,"+").setParameterLength(2,1/0).setName("add"),At=U(We,"-").setParameterLength(2,1/0).setName("sub"),fe=U(We,"*").setParameterLength(2,1/0).setName("mul"),Us=U(We,"/").setParameterLength(2,1/0).setName("div"),xl=U(We,"%").setParameterLength(2).setName("mod"),_g=U(We,"==").setParameterLength(2).setName("equal"),OT=U(We,"!=").setParameterLength(2).setName("notEqual"),BT=U(We,"<").setParameterLength(2).setName("lessThan"),IT=U(We,">").setParameterLength(2).setName("greaterThan"),LT=U(We,"<=").setParameterLength(2).setName("lessThanEqual"),UT=U(We,">=").setParameterLength(2).setName("greaterThanEqual"),kT=U(We,"&&").setParameterLength(2,1/0).setName("and"),zT=U(We,"||").setParameterLength(2,1/0).setName("or"),GT=U(We,"!").setParameterLength(1).setName("not"),VT=U(We,"^^").setParameterLength(2).setName("xor"),HT=U(We,"&").setParameterLength(2).setName("bitAnd"),WT=U(We,"~").setParameterLength(2).setName("bitNot"),$T=U(We,"|").setParameterLength(2).setName("bitOr"),jT=U(We,"^").setParameterLength(2).setName("bitXor"),qT=U(We,"<<").setParameterLength(2).setName("shiftLeft"),YT=U(We,">>").setParameterLength(2).setName("shiftRight"),XT=L(([o])=>(o.addAssign(1),o)),ZT=L(([o])=>(o.subAssign(1),o)),KT=L(([o])=>{const e=ke(o).toConst();return o.addAssign(1),e}),QT=L(([o])=>{const e=ke(o).toConst();return o.subAssign(1),e});O("add",Dt);O("sub",At);O("mul",fe);O("div",Us);O("mod",xl);O("equal",_g);O("notEqual",OT);O("lessThan",BT);O("greaterThan",IT);O("lessThanEqual",LT);O("greaterThanEqual",UT);O("and",kT);O("or",zT);O("not",GT);O("xor",VT);O("bitAnd",HT);O("bitNot",WT);O("bitOr",$T);O("bitXor",jT);O("shiftLeft",qT);O("shiftRight",YT);O("incrementBefore",XT);O("decrementBefore",ZT);O("increment",KT);O("decrement",QT);const JT=(o,e)=>(console.warn('THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.'),xl(o,e)),eS=(o,e)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),xl(ke(o),ke(e)));O("remainder",JT);O("modInt",eS);class A extends nt{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===A.MAX||e===A.MIN)&&arguments.length>3){let n=new A(e,t,s);for(let r=2;r<arguments.length-1;r++)n=new A(e,n,arguments[r]);t=n,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,n=e.isMatrix(t)?0:e.getTypeLength(t),r=e.isMatrix(s)?0:e.getTypeLength(s),a=e.isMatrix(i)?0:e.getTypeLength(i);return n>r&&n>a?t:r>a?s:a>n?i:t}getNodeType(e){const t=this.method;return t===A.LENGTH||t===A.DISTANCE||t===A.DOT?"float":t===A.CROSS?"vec3":t===A.ALL||t===A.ANY?"bool":t===A.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let n=null;if(i===A.ONE_MINUS)n=At(1,t);else if(i===A.RECIPROCAL)n=Us(1,t);else if(i===A.DIFFERENCE)n=ns(At(t,s));else if(i===A.TRANSFORM_DIRECTION){let r=t,a=s;e.isMatrix(r.getNodeType(e))?a=ne(I(a),0):r=ne(I(r),0);const l=fe(r,a).xyz;n=So(l)}return n!==null?n:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const n=this.getNodeType(e),r=this.getInputType(e),a=this.aNode,l=this.bNode,c=this.cNode,h=e.renderer.coordinateSystem;if(i===A.NEGATE)return e.format("( - "+a.build(e,r)+" )",n,t);{const u=[];return i===A.CROSS?u.push(a.build(e,n),l.build(e,n)):h===Ut&&i===A.STEP?u.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":r),l.build(e,r)):h===Ut&&(i===A.MIN||i===A.MAX)?u.push(a.build(e,r),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":r)):i===A.REFRACT?u.push(a.build(e,r),l.build(e,r),c.build(e,"float")):i===A.MIX?u.push(a.build(e,r),l.build(e,r),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":r)):(h===Oi&&i===A.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===A.DFDX||i===A.DFDY)&&(console.warn(`THREE.TSL: '${i}' is not supported in the ${e.shaderStage} stage.`),i="/*"+i+"*/"),u.push(a.build(e,r)),l!==null&&u.push(l.build(e,r)),c!==null&&u.push(c.build(e,r))),e.format(`${e.getMethod(i,n)}( ${u.join(", ")} )`,n,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}A.ALL="all";A.ANY="any";A.RADIANS="radians";A.DEGREES="degrees";A.EXP="exp";A.EXP2="exp2";A.LOG="log";A.LOG2="log2";A.SQRT="sqrt";A.INVERSE_SQRT="inversesqrt";A.FLOOR="floor";A.CEIL="ceil";A.NORMALIZE="normalize";A.FRACT="fract";A.SIN="sin";A.COS="cos";A.TAN="tan";A.ASIN="asin";A.ACOS="acos";A.ATAN="atan";A.ABS="abs";A.SIGN="sign";A.LENGTH="length";A.NEGATE="negate";A.ONE_MINUS="oneMinus";A.DFDX="dFdx";A.DFDY="dFdy";A.ROUND="round";A.RECIPROCAL="reciprocal";A.TRUNC="trunc";A.FWIDTH="fwidth";A.TRANSPOSE="transpose";A.BITCAST="bitcast";A.EQUALS="equals";A.MIN="min";A.MAX="max";A.STEP="step";A.REFLECT="reflect";A.DISTANCE="distance";A.DIFFERENCE="difference";A.DOT="dot";A.CROSS="cross";A.POW="pow";A.TRANSFORM_DIRECTION="transformDirection";A.MIX="mix";A.CLAMP="clamp";A.REFRACT="refract";A.SMOOTHSTEP="smoothstep";A.FACEFORWARD="faceforward";const tS=B(1e-6),sS=B(Math.PI),iS=U(A,A.ALL).setParameterLength(1),nS=U(A,A.ANY).setParameterLength(1),rS=U(A,A.RADIANS).setParameterLength(1),oS=U(A,A.DEGREES).setParameterLength(1),bg=U(A,A.EXP).setParameterLength(1),To=U(A,A.EXP2).setParameterLength(1),Tg=U(A,A.LOG).setParameterLength(1),ii=U(A,A.LOG2).setParameterLength(1),wu=U(A,A.SQRT).setParameterLength(1),aS=U(A,A.INVERSE_SQRT).setParameterLength(1),un=U(A,A.FLOOR).setParameterLength(1),Mu=U(A,A.CEIL).setParameterLength(1),So=U(A,A.NORMALIZE).setParameterLength(1),Ui=U(A,A.FRACT).setParameterLength(1),_s=U(A,A.SIN).setParameterLength(1),wi=U(A,A.COS).setParameterLength(1),lS=U(A,A.TAN).setParameterLength(1),cS=U(A,A.ASIN).setParameterLength(1),Sg=U(A,A.ACOS).setParameterLength(1),vg=U(A,A.ATAN).setParameterLength(1,2),ns=U(A,A.ABS).setParameterLength(1),ll=U(A,A.SIGN).setParameterLength(1),ni=U(A,A.LENGTH).setParameterLength(1),hS=U(A,A.NEGATE).setParameterLength(1),uS=U(A,A.ONE_MINUS).setParameterLength(1),wg=U(A,A.DFDX).setParameterLength(1),Mg=U(A,A.DFDY).setParameterLength(1),dS=U(A,A.ROUND).setParameterLength(1),pS=U(A,A.RECIPROCAL).setParameterLength(1),fS=U(A,A.TRUNC).setParameterLength(1),mS=U(A,A.FWIDTH).setParameterLength(1),gS=U(A,A.TRANSPOSE).setParameterLength(1),yS=(o,e)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),_g(o,e)),fr=U(A,A.MIN).setParameterLength(2,1/0),vt=U(A,A.MAX).setParameterLength(2,1/0),Cg=U(A,A.STEP).setParameterLength(2),xS=U(A,A.REFLECT).setParameterLength(2),_S=U(A,A.DISTANCE).setParameterLength(2),bS=U(A,A.DIFFERENCE).setParameterLength(2),Cu=U(A,A.DOT).setParameterLength(2),Eg=U(A,A.CROSS).setParameterLength(2),_l=U(A,A.POW).setParameterLength(2),Ag=U(A,A.POW,2).setParameterLength(1),TS=U(A,A.POW,3).setParameterLength(1),SS=U(A,A.POW,4).setParameterLength(1),vS=U(A,A.TRANSFORM_DIRECTION).setParameterLength(2),wS=o=>fe(ll(o),_l(ns(o),1/3)),Rg=o=>Cu(o,o),Ge=U(A,A.MIX).setParameterLength(3),ai=(o,e=0,t=1)=>k(new A(A.CLAMP,k(o),k(e),k(t))),Ng=o=>ai(o),Pg=U(A,A.REFRACT).setParameterLength(3),Bi=U(A,A.SMOOTHSTEP).setParameterLength(3),MS=U(A,A.FACEFORWARD).setParameterLength(3),CS=L(([o])=>{const s=43758.5453,i=Cu(o.xy,H(12.9898,78.233)),n=xl(i,sS);return Ui(_s(n).mul(s))}),ES=(o,e,t)=>Ge(e,t,o),AS=(o,e,t)=>Bi(e,t,o),RS=(o,e)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),vg(o,e));O("all",iS);O("any",nS);O("equals",yS);O("radians",rS);O("degrees",oS);O("exp",bg);O("exp2",To);O("log",Tg);O("log2",ii);O("sqrt",wu);O("inverseSqrt",aS);O("floor",un);O("ceil",Mu);O("normalize",So);O("fract",Ui);O("sin",_s);O("cos",wi);O("tan",lS);O("asin",cS);O("acos",Sg);O("atan",vg);O("abs",ns);O("sign",ll);O("length",ni);O("lengthSq",Rg);O("negate",hS);O("oneMinus",uS);O("dFdx",wg);O("dFdy",Mg);O("round",dS);O("reciprocal",pS);O("trunc",fS);O("fwidth",mS);O("atan2",RS);O("min",fr);O("max",vt);O("step",Cg);O("reflect",xS);O("distance",_S);O("dot",Cu);O("cross",Eg);O("pow",_l);O("pow2",Ag);O("pow3",TS);O("pow4",SS);O("transformDirection",vS);O("mix",ES);O("clamp",ai);O("refract",Pg);O("smoothstep",AS);O("faceForward",MS);O("difference",bS);O("saturate",Ng);O("cbrt",wS);O("transpose",gS);O("rand",CS);class NS extends re{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(t===void 0)return this.setup(e),this.getNodeType(e);const i=t.getNodeType(e);if(s!==null){const n=s.getNodeType(e);if(e.getTypeLength(n)>e.getTypeLength(i))return n}return i}setup(e){const t=this.condNode.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,n=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=n,i!==null&&(e.getDataFromNode(i).parentNodeBlock=n);const r=e.getNodeProperties(this);r.condNode=t,r.ifNode=s.context({nodeBlock:s}),r.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;const{condNode:n,ifNode:r,elseNode:a}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",h=c?dg(s).build(e):"";i.nodeProperty=h;const u=n.build(e,"bool");e.addFlowCode(`
|
|
51
51
|
${e.tab}if ( ${u} ) {
|
|
52
52
|
|
|
53
53
|
`).addFlowTab();let d=r.build(e,s);if(d&&(c?d=h+" = "+d+";":(d="return "+d+";",l===null&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),d="// "+d))),e.removeFlowTab().addFlowCode(e.tab+" "+d+`
|
|
@@ -60,27 +60,27 @@ ${e.tab}if ( ${u} ) {
|
|
|
60
60
|
|
|
61
61
|
`)}else e.addFlowCode(`
|
|
62
62
|
|
|
63
|
-
`);return e.format(h,s,t)}}const Tt=U(oS).setParameterLength(2,3);O("select",Tt);const aS=(...o)=>(console.warn("THREE.TSL: cond() has been renamed to select()."),Tt(...o));O("cond",aS);class Ag extends re{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Mu=U(Ag).setParameterLength(1,2),lS=(o,e)=>Mu(o,{label:e});O("context",Mu);O("label",lS);class Oa extends re{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:n}=e,r=n.backend.isWebGPUBackend===!0;let a=!1,l=!1;i&&(a=e.isDeterministic(t),l=r?i:a);const c=e.getVectorType(this.getNodeType(e)),h=t.build(e,c),u=e.getVarFromNode(this,s,c,void 0,l),d=e.getPropertyName(u);let p=d;if(l)if(r)p=a?`const ${d}`:`let ${d}`;else{const f=e.getArrayCount(t);p=`const ${e.getVar(u.type,d,f)}`}return e.addLineFlowCode(`${p} = ${h}`,this),d}}const Cu=U(Oa),cS=(o,e=null)=>Cu(o,e).toStack(),hS=(o,e=null)=>Cu(o,e,!0).toStack();O("toVar",cS);O("toConst",hS);const uS=o=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Cu(o));O("temp",uS);class dS extends re{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(s===void 0){const i=this.name,n=this.getNodeType(e),r=this.interpolationType,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,n,r,a),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation=e.shaderStage==="fragment"),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Vo.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Vo.VERTEX,this.node)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(t.propertyName===void 0){const i=this.getNodeType(e),n=e.getPropertyName(s,Vo.VERTEX);e.flowNodeFromShaderStage(Vo.VERTEX,this.node,i,n),t.propertyName=n}return e.getPropertyName(s)}}const ws=U(dS).setParameterLength(1,2),pS=o=>ws(o);O("toVarying",ws);O("toVertexStage",pS);O("varying",(...o)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),ws(...o)));O("vertexStage",(...o)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),ws(...o)));const fS=L(([o])=>{const e=o.mul(.9478672986).add(.0521327014).pow(2.4),t=o.mul(.0773993808),s=o.lessThanEqual(.04045);return Ve(e,t,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),mS=L(([o])=>{const e=o.pow(.41666).mul(1.055).sub(.055),t=o.mul(12.92),s=o.lessThanEqual(.0031308);return Ve(e,t,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Eu="WorkingColorSpace",gS="OutputColorSpace";class Rg extends nt{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===Eu?Ue.workingColorSpace:t===gS?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let n=t;return Ue.enabled===!1||s===i||!s||!i||(Ue.getTransfer(s)===te&&(n=ne(fS(n.rgb),n.a)),Ue.getPrimaries(s)!==Ue.getPrimaries(i)&&(n=ne(Ft(Ue._getMatrix(new Ht,s,i)).mul(n.rgb),n.a)),Ue.getTransfer(i)===te&&(n=ne(mS(n.rgb),n.a))),n}}const yS=(o,e)=>k(new Rg(k(o),Eu,e)),Au=(o,e)=>k(new Rg(k(o),e,Eu));O("workingToColorSpace",yS);O("colorSpaceToWorking",Au);let xS=class extends Mo{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Ng extends re{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=he.OBJECT}setGroup(e){return this.group=e,this}element(e){return k(new xS(this,k(e)))}setNodeType(e){const t=K(null,e).getSelf();this.group!==null&&t.setGroup(this.group),this.node=t}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const _S=(o,e,t)=>k(new Ng(o,e,t));class bS extends Ng{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(Q)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const TS=(o,e,t=null)=>k(new bS(o,e,t));class SS extends nt{static get type(){return"ToneMappingNode"}constructor(e,t=wS,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Ka(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(s===Kn)return t;let i=null;const n=e.renderer.library.getToneMappingFunction(s);return n!==null?i=ne(n(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const vS=(o,e,t)=>k(new SS(o,k(e),k(t))),wS=TS("toneMappingExposure","float");O("toneMapping",(o,e,t)=>vS(e,t,o));const Mt=new N;class Ru{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}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,s=this.data.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.applyMatrix4(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.applyNormalMatrix(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.transformDirection(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=ae(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Rt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Rt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Rt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=n,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return new ls(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Ru(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,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}}}class Pg{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Qa,this.updateRanges=[],this.version=0,this.uuid=Qs()}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,s){e*=this.stride,s*=t.stride;for(let i=0,n=this.stride;i<n;i++)this.array[e+i]=t.array[s+i];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=Qs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}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=Qs()),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}}}class MS extends pu{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Qa,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(this.bufferStride===0&&this.bufferOffset===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),s=this.value,i=e.getTypeLength(t),n=this.bufferStride||i,r=this.bufferOffset,a=s.isInterleavedBuffer===!0?s:new Pg(s,n),l=new Ru(a,i,r);a.setUsage(this.usage),this.attribute=l,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let n=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=i,n=i):n=ws(this).build(e,t),n}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const Nu=(o,e=null,t=0,s=0)=>k(new MS(o,e,t,s)),CS=(o,e=null,t=0,s=0)=>Nu(o,e,t,s).setUsage(jn),ap=(o,e=null,t=0,s=0)=>Nu(o,e,t,s).setInstanced(!0),lp=(o,e=null,t=0,s=0)=>CS(o,e,t,s).setInstanced(!0);O("toAttribute",o=>Nu(o.value));class ES extends re{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=he.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let i=1;i<t.length;i++)s*=t[i];this.dispatchCount=Math.ceil(e/s)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){const s=e.getNodeProperties(this);s.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if(s==="compute"){const i=this.computeNode.build(e,"void");i!==""&&e.addLineFlowCode(i,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const AS=(o,e,t)=>k(new ES(k(o),e,t));O("compute",AS);class RS extends re{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const n=this.node.build(e,...t);return e.setCache(s),n}}const Ba=(o,e)=>k(new RS(k(o),e)),NS=(o,e)=>o.context({namespace:e});O("cache",Ba);class PS extends re{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const FS=U(PS).setParameterLength(2);O("bypass",FS);class Fg extends re{static get type(){return"RemapNode"}constructor(e,t,s,i=B(0),n=B(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=n,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:n,doClamp:r}=this;let a=e.sub(t).div(s.sub(t));return r===!0&&(a=a.clamp()),a.mul(n.sub(i)).add(i)}}const DS=U(Fg,null,null,{doClamp:!1}).setParameterLength(3,5),OS=U(Fg).setParameterLength(3,5);O("remap",DS);O("remapClamp",OS);class Ia extends re{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if(s==="void")e.addLineFlowCode(i,this);else return e.format(i,s,t)}}const pr=U(Ia).setParameterLength(1,2),BS=o=>(o?Tt(o,pr("discard")):pr("discard")).toStack();O("discard",BS);class IS extends nt{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(this.toneMapping!==null?this.toneMapping:e.toneMapping)||Kn,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||ri;return s!==Kn&&(t=t.toneMapping(s)),i!==ri&&i!==Ue.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const LS=(o,e=null,t=null)=>k(new IS(k(o),e,t));O("renderOutput",LS);class US extends nt{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e),i="--- TSL debug - "+e.shaderStage+" shader ---",n="-".repeat(i.length);let r="";return r+="// #"+i+`#
|
|
63
|
+
`);return e.format(h,s,t)}}const Tt=U(NS).setParameterLength(2,3);O("select",Tt);const PS=(...o)=>(console.warn("THREE.TSL: cond() has been renamed to select()."),Tt(...o));O("cond",PS);class Fg extends re{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Eu=U(Fg).setParameterLength(1,2),FS=(o,e)=>Eu(o,{label:e});O("context",Eu);O("label",FS);class Ia extends re{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:n}=e,r=n.backend.isWebGPUBackend===!0;let a=!1,l=!1;i&&(a=e.isDeterministic(t),l=r?i:a);const c=e.getVectorType(this.getNodeType(e)),h=t.build(e,c),u=e.getVarFromNode(this,s,c,void 0,l),d=e.getPropertyName(u);let p=d;if(l)if(r)p=a?`const ${d}`:`let ${d}`;else{const f=e.getArrayCount(t);p=`const ${e.getVar(u.type,d,f)}`}return e.addLineFlowCode(`${p} = ${h}`,this),d}}const Au=U(Ia),DS=(o,e=null)=>Au(o,e).toStack(),OS=(o,e=null)=>Au(o,e,!0).toStack();O("toVar",DS);O("toConst",OS);const BS=o=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Au(o));O("temp",BS);class IS extends re{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(s===void 0){const i=this.name,n=this.getNodeType(e),r=this.interpolationType,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,n,r,a),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation=e.shaderStage==="fragment"),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Vo.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Vo.VERTEX,this.node)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e);if(t.propertyName===void 0){const i=this.getNodeType(e),n=e.getPropertyName(s,Vo.VERTEX);e.flowNodeFromShaderStage(Vo.VERTEX,this.node,i,n),t.propertyName=n}return e.getPropertyName(s)}}const ws=U(IS).setParameterLength(1,2),LS=o=>ws(o);O("toVarying",ws);O("toVertexStage",LS);O("varying",(...o)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),ws(...o)));O("vertexStage",(...o)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),ws(...o)));const US=L(([o])=>{const e=o.mul(.9478672986).add(.0521327014).pow(2.4),t=o.mul(.0773993808),s=o.lessThanEqual(.04045);return Ge(e,t,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),kS=L(([o])=>{const e=o.pow(.41666).mul(1.055).sub(.055),t=o.mul(12.92),s=o.lessThanEqual(.0031308);return Ge(e,t,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ru="WorkingColorSpace",zS="OutputColorSpace";class Dg extends nt{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===Ru?Ue.workingColorSpace:t===zS?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let n=t;return Ue.enabled===!1||s===i||!s||!i||(Ue.getTransfer(s)===te&&(n=ne(US(n.rgb),n.a)),Ue.getPrimaries(s)!==Ue.getPrimaries(i)&&(n=ne(Ft(Ue._getMatrix(new Ht,s,i)).mul(n.rgb),n.a)),Ue.getTransfer(i)===te&&(n=ne(kS(n.rgb),n.a))),n}}const GS=(o,e)=>k(new Dg(k(o),Ru,e)),Nu=(o,e)=>k(new Dg(k(o),e,Ru));O("workingToColorSpace",GS);O("colorSpaceToWorking",Nu);let VS=class extends Co{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class Og extends re{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=ue.OBJECT}setGroup(e){return this.group=e,this}element(e){return k(new VS(this,k(e)))}setNodeType(e){const t=Q(null,e).getSelf();this.group!==null&&t.setGroup(this.group),this.node=t}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const HS=(o,e,t)=>k(new Og(o,e,t));class WS extends Og{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(K)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const $S=(o,e,t=null)=>k(new WS(o,e,t));class jS extends nt{static get type(){return"ToneMappingNode"}constructor(e,t=YS,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return el(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,s=this.toneMapping;if(s===er)return t;let i=null;const n=e.renderer.library.getToneMappingFunction(s);return n!==null?i=ne(n(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const qS=(o,e,t)=>k(new jS(o,k(e),k(t))),YS=$S("toneMappingExposure","float");O("toneMapping",(o,e,t)=>qS(e,t,o));const Mt=new N;class Pu{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}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,s=this.data.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.applyMatrix4(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.applyNormalMatrix(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Mt.fromBufferAttribute(this,t),Mt.transformDirection(e),this.setXYZ(t,Mt.x,Mt.y,Mt.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=ae(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ae(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ae(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=Rt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Rt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Rt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Rt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ae(t,this.array),s=ae(s,this.array),i=ae(i,this.array),n=ae(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=n,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return new ls(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Pu(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let n=0;n<this.itemSize;n++)t.push(this.data.array[i+n])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,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}}}class Bg{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Ja,this.updateRanges=[],this.version=0,this.uuid=Ks()}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,s){e*=this.stride,s*=t.stride;for(let i=0,n=this.stride;i<n;i++)this.array[e+i]=t.array[s+i];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=Ks()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}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=Ks()),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}}}class XS extends mu{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Ja,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(this.bufferStride===0&&this.bufferOffset===0){let t=e.globalCache.getData(this.value);return t===void 0&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),s=this.value,i=e.getTypeLength(t),n=this.bufferStride||i,r=this.bufferOffset,a=s.isInterleavedBuffer===!0?s:new Bg(s,n),l=new Pu(a,i,r);a.setUsage(this.usage),this.attribute=l,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let n=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=i,n=i):n=ws(this).build(e,t),n}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const Fu=(o,e=null,t=0,s=0)=>k(new XS(o,e,t,s)),ZS=(o,e=null,t=0,s=0)=>Fu(o,e,t,s).setUsage(qn),hp=(o,e=null,t=0,s=0)=>Fu(o,e,t,s).setInstanced(!0),up=(o,e=null,t=0,s=0)=>ZS(o,e,t,s).setInstanced(!0);O("toAttribute",o=>Fu(o.value));class KS extends re{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=ue.OBJECT,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let i=1;i<t.length;i++)s*=t[i];this.dispatchCount=Math.ceil(e/s)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){const s=e.getNodeProperties(this);s.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if(s==="compute"){const i=this.computeNode.build(e,"void");i!==""&&e.addLineFlowCode(i,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const QS=(o,e,t)=>k(new KS(k(o),e,t));O("compute",QS);class JS extends re{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const n=this.node.build(e,...t);return e.setCache(s),n}}const La=(o,e)=>k(new JS(k(o),e)),ev=(o,e)=>o.context({namespace:e});O("cache",La);class tv extends re{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const sv=U(tv).setParameterLength(2);O("bypass",sv);class Ig extends re{static get type(){return"RemapNode"}constructor(e,t,s,i=B(0),n=B(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=n,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:n,doClamp:r}=this;let a=e.sub(t).div(s.sub(t));return r===!0&&(a=a.clamp()),a.mul(n.sub(i)).add(i)}}const iv=U(Ig,null,null,{doClamp:!1}).setParameterLength(3,5),nv=U(Ig).setParameterLength(3,5);O("remap",iv);O("remapClamp",nv);class Ua extends re{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if(s==="void")e.addLineFlowCode(i,this);else return e.format(i,s,t)}}const mr=U(Ua).setParameterLength(1,2),rv=o=>(o?Tt(o,mr("discard")):mr("discard")).toStack();O("discard",rv);class ov extends nt{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const s=(this.toneMapping!==null?this.toneMapping:e.toneMapping)||er,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||ri;return s!==er&&(t=t.toneMapping(s)),i!==ri&&i!==Ue.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const av=(o,e=null,t=null)=>k(new ov(k(o),e,t));O("renderOutput",av);class lv extends nt{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e),i="--- TSL debug - "+e.shaderStage+" shader ---",n="-".repeat(i.length);let r="";return r+="// #"+i+`#
|
|
64
64
|
`,r+=e.flow.code.replace(/^\t/mg,"")+`
|
|
65
65
|
`,r+="/* ... */ "+s+` /* ... */
|
|
66
66
|
`,r+="// #"+n+`#
|
|
67
|
-
`,t!==null?t(e,r):console.log(r),s}}const
|
|
67
|
+
`,t!==null?t(e,r):console.log(r),s}}const cv=(o,e=null)=>k(new lv(k(o),e));O("debug",cv);class Lg extends re{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(t===null){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){const n=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(n),a=e.getAttribute(t,r);return e.shaderStage==="vertex"?e.format(a.name,r,s):ws(this).build(e,s)}else return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Ii=(o,e=null)=>k(new Lg(o,e));class Ve extends re{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i;if(s===Ve.VERTEX)i=e.getVertexIndex();else if(s===Ve.INSTANCE)i=e.getInstanceIndex();else if(s===Ve.DRAW)i=e.getDrawIndex();else if(s===Ve.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Ve.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(s===Ve.SUBGROUP)i=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+s);let n;return e.shaderStage==="vertex"||e.shaderStage==="compute"?n=i:n=ws(this).build(e,t),n}}Ve.VERTEX="vertex";Ve.INSTANCE="instance";Ve.SUBGROUP="subgroup";Ve.INVOCATION_LOCAL="invocationLocal";Ve.INVOCATION_SUBGROUP="invocationSubgroup";Ve.DRAW="draw";const hv=V(Ve,Ve.VERTEX),Du=V(Ve,Ve.INSTANCE);Ve.SUBGROUP;Ve.INVOCATION_SUBGROUP;Ve.INVOCATION_LOCAL;const uv=V(Ve,Ve.DRAW);class dv extends Re{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class pv extends re{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new eo(t);return this._currentCond=Tt(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new eo(t),i=Tt(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new eo(e),this}Switch(e){return this._expressionNode=k(e),this}Case(...e){const t=[];if(e.length>=2)for(let a=0;a<e.length-1;a++)t.push(this._expressionNode.equal(k(e[a])));else throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=e[e.length-1],i=new eo(s);let n=t[0];for(let a=1;a<t.length;a++)n=n.or(t[a]);const r=Tt(n,i);return this._currentCond===null?(this._currentCond=r,this.add(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}build(e,...t){const s=lg();il(this);const i=e.buildStage;for(const n of this.nodes)if(i==="setup")n.build(e);else if(i==="analyze")n.build(e,this);else if(i==="generate"){const r=e.getDataFromNode(n,"any").stages,a=r&&r[e.shaderStage];if(n.isVarNode&&a&&a.length===1&&a[0]&&a[0].isStackNode)continue;n.build(e,"void")}return il(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("THREE.TSL: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("THREE.TSL: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const ec=U(pv).setParameterLength(0,1);class fv extends re{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){const t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;const s={};for(let r=0,a=this.params.length-1;r<a;r++){const l=this.params[r],c=l.isNode!==!0&&l.name||this.getVarName(r),h=l.isNode!==!0&&l.type||"int";s[c]=mr(c,h)}const i=e.addStack();t.returnsNode=this.params[this.params.length-1](s,e),t.stackNode=i;const n=this.params[0];return n.isNode!==!0&&typeof n.update=="function"&&(t.updateNode=L(this.params[0].update)(s)),e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let a=0,l=s.length-1;a<l;a++){const c=s[a];let h=!1,u=null,d=null,p=null,f=null,m=null,x=null;c.isNode?c.getNodeType(e)==="bool"?(h=!0,f="bool",d=c.build(e,f)):(f="int",p=this.getVarName(a),u="0",d=c.build(e,f),m="<"):(f=c.type||"int",p=c.name||this.getVarName(a),u=c.start,d=c.end,m=c.condition,x=c.update,typeof u=="number"?u=e.generateConst(f,u):u&&u.isNode&&(u=u.build(e,f)),typeof d=="number"?d=e.generateConst(f,d):d&&d.isNode&&(d=d.build(e,f)),u!==void 0&&d===void 0?(u=u+" - 1",d="0",m=">="):d!==void 0&&u===void 0&&(u="0",m="<"),m===void 0&&(Number(u)>Number(d)?m=">=":m="<"));let g;if(h)g=`while ( ${d} )`;else{const _={start:u,end:d},b=_.start,T=_.end;let S;const C=()=>m.includes("<")?"+=":"-=";if(x!=null)switch(typeof x){case"function":S=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":S=p+" "+C()+" "+e.generateConst(f,x);break;case"string":S=p+" "+x;break;default:x.isNode?S=p+" "+C()+" "+x.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),S="break /* invalid update */")}else f==="int"||f==="uint"?x=m.includes("<")?"++":"--":x=C()+" 1.",S=p+" "+x;const w=e.getVar(f,p)+" = "+b,R=p+" "+m+" "+T;g=`for ( ${w}; ${R}; ${S} )`}e.addFlowCode((a===0?`
|
|
68
68
|
`:"")+e.tab+g+` {
|
|
69
69
|
|
|
70
70
|
`).addFlowTab()}const n=i.build(e,"void"),r=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode(`
|
|
71
71
|
`+e.tab+n);for(let a=0,l=this.params.length-1;a<l;a++)e.addFlowCode((a===0?"":e.tab)+`}
|
|
72
72
|
|
|
73
|
-
`).removeFlowTab();return e.addFlowTab(),r}}const Ts=(...o)=>k(new WS(tr(o,"int"))).toStack(),$S=()=>pr("break").toStack();class Eo{constructor(e=new N(1/0,1/0,1/0),t=new N(-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,s=e.length;t<s;t+=3)this.expandByPoint(fs.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(fs.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=fs.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),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);const s=e.geometry;if(s!==void 0){const n=s.getAttribute("position");if(t===!0&&n!==void 0&&e.isInstancedMesh!==!0)for(let r=0,a=n.count;r<a;r++)e.isMesh===!0?e.getVertexPosition(r,fs):fs.fromBufferAttribute(n,r),fs.applyMatrix4(e.matrixWorld),this.expandByPoint(fs);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Go.copy(e.boundingBox)):(s.boundingBox===null&&s.computeBoundingBox(),Go.copy(s.boundingBox)),Go.applyMatrix4(e.matrixWorld),this.union(Go)}const i=e.children;for(let n=0,r=i.length;n<r;n++)this.expandByObject(i[n],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,fs),fs.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Ar),Ho.subVectors(this.max,Ar),En.subVectors(e.a,Ar),An.subVectors(e.b,Ar),Rn.subVectors(e.c,Ar),fi.subVectors(An,En),mi.subVectors(Rn,An),Gi.subVectors(En,Rn);let t=[0,-fi.z,fi.y,0,-mi.z,mi.y,0,-Gi.z,Gi.y,fi.z,0,-fi.x,mi.z,0,-mi.x,Gi.z,0,-Gi.x,-fi.y,fi.x,0,-mi.y,mi.x,0,-Gi.y,Gi.x,0];return!Kl(t,En,An,Rn,Ho)||(t=[1,0,0,0,1,0,0,0,1],!Kl(t,En,An,Rn,Ho))?!1:(Wo.crossVectors(fi,mi),t=[Wo.x,Wo.y,Wo.z],Kl(t,En,An,Rn,Ho))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fs).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(fs).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:(Hs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Hs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Hs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Hs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Hs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Hs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Hs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Hs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Hs),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}}const Hs=[new N,new N,new N,new N,new N,new N,new N,new N],fs=new N,Go=new Eo,En=new N,An=new N,Rn=new N,fi=new N,mi=new N,Gi=new N,Ar=new N,Ho=new N,Wo=new N,Hi=new N;function Kl(o,e,t,s,i){for(let n=0,r=o.length-3;n<=r;n+=3){Hi.fromArray(o,n);const a=i.x*Math.abs(Hi.x)+i.y*Math.abs(Hi.y)+i.z*Math.abs(Hi.z),l=e.dot(Hi),c=t.dot(Hi),h=s.dot(Hi);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}const jS=new Eo,Rr=new N,Jl=new N;class yl{constructor(e=new N,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){const s=this.center;t!==void 0?s.copy(t):jS.setFromPoints(e).getCenter(s);let i=0;for(let n=0,r=e.length;n<r;n++)i=Math.max(i,s.distanceToSquared(e[n]));return this.radius=Math.sqrt(i),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){const 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){const s=this.center.distanceToSquared(e);return t.copy(e),s>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=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;Rr.subVectors(e,this.center);const t=Rr.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),i=(s-this.radius)*.5;this.center.addScaledVector(Rr,i/s),this.radius+=i}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):(Jl.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Rr.copy(e.center).add(Jl)),this.expandByPoint(Rr.copy(e.center).sub(Jl))),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}}const cp=new yl;class Pe extends re{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=he.OBJECT,this.uniformNode=new Co(null)}getNodeType(){const e=this.scope;if(e===Pe.WORLD_MATRIX)return"mat4";if(e===Pe.POSITION||e===Pe.VIEW_POSITION||e===Pe.DIRECTION||e===Pe.SCALE)return"vec3";if(e===Pe.RADIUS)return"float"}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Pe.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Pe.POSITION)s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Pe.SCALE)s.value=s.value||new N,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Pe.DIRECTION)s.value=s.value||new N,t.getWorldDirection(s.value);else if(i===Pe.VIEW_POSITION){const n=e.camera;s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(n.matrixWorldInverse)}else if(i===Pe.RADIUS){const n=e.object.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),cp.copy(n.boundingSphere).applyMatrix4(t.matrixWorld),s.value=cp.radius}}generate(e){const t=this.scope;return t===Pe.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Pe.POSITION||t===Pe.VIEW_POSITION||t===Pe.DIRECTION||t===Pe.SCALE?this.uniformNode.nodeType="vec3":t===Pe.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Pe.WORLD_MATRIX="worldMatrix";Pe.POSITION="position";Pe.SCALE="scale";Pe.VIEW_POSITION="viewPosition";Pe.DIRECTION="direction";Pe.RADIUS="radius";const qS=U(Pe,Pe.POSITION).setParameterLength(1);class Og extends Co{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Bg=(o,e,t)=>k(new Og(o,e,t));class YS extends Mo{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class XS extends Og{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?el(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=he.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if(s==="float"||s==="int"||s==="uint")for(let i=0;i<e.length;i++){const n=i*4;t[n]=e[i]}else if(s==="color")for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.r,t[n+1]=r.g,t[n+2]=r.b||0}else if(s==="mat2")for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+3]=r.elements[3]}else if(s==="mat3")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+4]=r.elements[3],t[n+5]=r.elements[4],t[n+6]=r.elements[5],t[n+8]=r.elements[6],t[n+9]=r.elements[7],t[n+10]=r.elements[8],t[n+15]=1}else if(s==="mat4")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];for(let a=0;a<r.elements.length;a++)t[n+a]=r.elements[a]}else for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.x,t[n+1]=r.y,t[n+2]=r.z||0,t[n+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const n=this.paddedType,r=e.getTypeLength(n);return s.charAt(0)==="i"&&(i=Int32Array),s.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*r),this.bufferCount=t,this.bufferType=n,super.setup(e)}element(e){return k(new YS(this,k(e)))}}const Os=(o,e)=>k(new XS(o,e));class ZS extends re{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const xl=U(ZS).setParameterLength(1),Ig=K(0,"uint").label("u_cameraIndex").setGroup(_u("cameraIndex")).toVarying("v_cameraIndex"),rn=K("float").label("cameraNear").setGroup(Q).onRenderUpdate(({camera:o})=>o.near),on=K("float").label("cameraFar").setGroup(Q).onRenderUpdate(({camera:o})=>o.far),Fu=L(({camera:o})=>{let e;if(o.isArrayCamera&&o.cameras.length>0){const t=[];for(const i of o.cameras)t.push(i.projectionMatrix);e=Os(t).setGroup(Q).label("cameraProjectionMatrices").element(o.isMultiViewCamera?xl("gl_ViewID_OVR"):Ig).toVar("cameraProjectionMatrix")}else e=K("mat4").label("cameraProjectionMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.projectionMatrix);return e}).once()(),hi=L(({camera:o})=>{let e;if(o.isArrayCamera&&o.cameras.length>0){const t=[];for(const i of o.cameras)t.push(i.matrixWorldInverse);e=Os(t).setGroup(Q).label("cameraViewMatrices").element(o.isMultiViewCamera?xl("gl_ViewID_OVR"):Ig).toVar("cameraViewMatrix")}else e=K("mat4").label("cameraViewMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.matrixWorldInverse);return e}).once()(),QS=K(new N).label("cameraPosition").setGroup(Q).onRenderUpdate(({camera:o},e)=>e.value.setFromMatrixPosition(o.matrixWorld));class ds extends Pe{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}ds.DIRECTION;const dn=G(ds,ds.WORLD_MATRIX);ds.POSITION;ds.SCALE;ds.VIEW_POSITION;ds.RADIUS;const KS=K(new Ht).onObjectUpdate(({object:o},e)=>e.value.getNormalMatrix(o.matrixWorld)),_l=L(o=>o.renderer.overrideNodes.modelViewMatrix||JS).once()().toVar("modelViewMatrix"),JS=hi.mul(dn),hp=L(o=>(o.context.isHighPrecisionModelViewMatrix=!0,K("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),up=L(o=>{const e=o.context.isHighPrecisionModelViewMatrix;return K("mat3").onObjectUpdate(({object:t,camera:s})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),bl=Ii("position","vec3"),bt=bl.toVarying("positionLocal"),dp=bl.toVarying("positionPrevious"),So=L(o=>dn.mul(bt).xyz.toVarying(o.getNamespace("v_positionWorld")),"vec3").once("POSITION")(),Lg=L(o=>bt.transformDirection(dn).toVarying(o.getNamespace("v_positionWorldDirection")).normalize().toVar("positionWorldDirection"),"vec3").once("POSITION")(),st=L(o=>o.context.setupPositionView().toVarying(o.getNamespace("v_positionView")),"vec3").once("POSITION")(),je=st.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class ev extends nt{static get type(){return"EquirectUVNode"}constructor(e=Lg){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan(e.x).mul(1/(Math.PI*2)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return H(t,s)}}const Ug=U(ev).setParameterLength(0,1);class tv extends re{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Ut&&s.side===Vt?"false":e.getFrontFacing()}}const sv=G(tv),Tl=B(sv).mul(2).sub(1),kg=Ii("normal","vec3"),ks=L(o=>o.geometry.hasAttribute("normal")===!1?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),I(0,1,0)):kg,"vec3").once()().toVar("normalLocal"),iv=st.dFdx().cross(st.dFdy()).normalize().toVar("normalFlat"),zs=L(o=>{let e;return o.material.flatShading===!0?e=iv:e=ws(zg(ks),"v_normalView").normalize(),e},"vec3").once()().toVar("normalView"),Du=L(o=>{let e=zs.transformDirection(hi);return o.material.flatShading!==!0&&(e=ws(e,"v_normalWorld")),e},"vec3").once()().normalize().toVar("normalWorld"),et=L(o=>{let e=o.context.setupNormal().context({getUV:null});return o.material.flatShading!==!0&&(e=e.mul(Tl)),e},"vec3").once()().toVar("transformedNormalView"),Ou=et.transformDirection(hi).toVar("transformedNormalWorld"),Jr=L(o=>{let e=o.context.setupClearcoatNormal().context({getUV:null});return o.material.flatShading!==!0&&(e=e.mul(Tl)),e},"vec3").once()().toVar("transformedClearcoatNormalView"),nv=L(([o,e=dn])=>{const t=Ft(e),s=o.div(I(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(s).xyz}),zg=L(([o],e)=>{const t=e.renderer.overrideNodes.modelNormalViewMatrix;if(t!==null)return t.transformDirection(o);const s=KS.mul(o);return hi.transformDirection(s)});class rv extends nt{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=I(je.z,0,je.x.negate()).normalize(),t=je.cross(e);return H(e.dot(et),t.dot(et)).mul(.495).add(.5)}}const ov=G(rv);class av extends Co{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=he.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&s.width!==void 0){const{width:i,height:n}=s;this.value=Math.log2(Math.max(i,n))}}}const lv=U(av).setParameterLength(1),cv=o=>k(o).mul(.5).add(.5);class hv extends nt{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if(this.getNodeType(e)==="vec2"){const n=t.cos(),r=t.sin();return xu(n,r,r.negate(),n).mul(s)}else{const n=t,r=sr(ne(1,0,0,0),ne(0,wi(n.x),_s(n.x).negate(),0),ne(0,_s(n.x),wi(n.x),0),ne(0,0,0,1)),a=sr(ne(wi(n.y),0,_s(n.y),0),ne(0,1,0,0),ne(_s(n.y).negate(),0,wi(n.y),0),ne(0,0,0,1)),l=sr(ne(wi(n.z),_s(n.z).negate(),0,0),ne(_s(n.z),wi(n.z),0,0),ne(0,0,1,0),ne(0,0,0,1));return r.mul(a).mul(l).mul(ne(s,1)).xyz}}}const Vg=U(hv).setParameterLength(2);let Nr,Pr;class Je extends re{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Je.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=he.NONE;return(this.scope===Je.SIZE||this.scope===Je.VIEWPORT)&&(e=he.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Je.VIEWPORT?t!==null?Pr.copy(t.viewport):(e.getViewport(Pr),Pr.multiplyScalar(e.getPixelRatio())):t!==null?(Nr.width=t.width,Nr.height=t.height):e.getDrawingBufferSize(Nr)}setup(){const e=this.scope;let t=null;return e===Je.SIZE?t=K(Nr||(Nr=new ce)):e===Je.VIEWPORT?t=K(Pr||(Pr=new ge)):t=H(Sl.div(kh)),t}generate(e){if(this.scope===Je.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(kh).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Je.COORDINATE="coordinate";Je.VIEWPORT="viewport";Je.SIZE="size";Je.UV="uv";const nr=G(Je,Je.UV),kh=G(Je,Je.SIZE),Sl=G(Je,Je.COORDINATE),ho=G(Je,Je.VIEWPORT);ho.zw;ho.xy;const Ao=(o=0)=>Ii("uv"+(o>0?o:""),"vec2");class uv extends re{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const rr=U(uv).setParameterLength(1,2),Gg=new St;class xr extends Co{static get type(){return"TextureNode"}constructor(e=Gg,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=he.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===Xe?"uvec4":this.value.type===Et?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Ao(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=K(this.value.matrix)),this._matrixUniform.mul(I(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?he.OBJECT:he.NONE,this}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.image instanceof ImageBitmap&&s.flipY===!0||s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0||s.isDepthTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(ke(rr(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||s.isTexture!==!0)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;(i===null||e.context.forceUVContext===!0)&&e.context.getUV&&(i=e.context.getUV(this,e)),i||(i=this.getDefaultUV()),this.updateMatrix===!0&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let n=this.levelNode;n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=n,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateSnippet(e,t,s,i,n,r,a,l){const c=this.value;let h;return i?h=e.generateTextureLevel(c,t,s,i,r):n?h=e.generateTextureBias(c,t,s,n,r):l?h=e.generateTextureGrad(c,t,s,l,r):a?h=e.generateTextureCompare(c,t,s,a,r):this.sampler===!1?h=e.generateTextureLoad(c,t,s,r):h=e.generateTexture(c,t,s,r),h}generate(e,t){const s=this.value,i=e.getNodeProperties(this),n=super.generate(e,"property");if(/^sampler/.test(t))return n+"_sampler";if(e.isReference(t))return n;{const r=e.getDataFromNode(this);let a=r.propertyName;if(a===void 0){const{uvNode:h,levelNode:u,biasNode:d,compareNode:p,depthNode:f,gradNode:m}=i,y=this.generateUV(e,h),g=u?u.build(e,"float"):null,_=d?d.build(e,"float"):null,b=f?f.build(e,"int"):null,T=p?p.build(e,"float"):null,S=m?[m[0].build(e,"vec2"),m[1].build(e,"vec2")]:null,C=e.getVarFromNode(this);a=e.getPropertyName(C);const w=this.generateSnippet(e,n,y,g,_,b,T,S);e.addLineFlowCode(`${a} = ${w}`,this),r.snippet=w,r.propertyName=a}let l=a;const c=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(l=Au(pr(l,c),s.colorSpace).setup(e).build(e,c)),e.format(l,c,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=k(e),t.referenceNode=this.getSelf(),k(t)}blur(e){const t=this.clone();t.biasNode=k(e).mul(lv(t)),t.referenceNode=this.getSelf();const s=t.value;return t.generateMipmaps===!1&&(s&&s.generateMipmaps===!1||s.minFilter===ut||s.magFilter===ut)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),k(t)}level(e){const t=this.clone();return t.levelNode=k(e),t.referenceNode=this.getSelf(),k(t)}size(e){return rr(this,e)}bias(e){const t=this.clone();return t.biasNode=k(e),t.referenceNode=this.getSelf(),k(t)}compare(e){const t=this.clone();return t.compareNode=k(e),t.referenceNode=this.getSelf(),k(t)}grad(e,t){const s=this.clone();return s.gradNode=[k(e),k(t)],s.referenceNode=this.getSelf(),k(s)}depth(e){const t=this.clone();return t.depthNode=k(e),t.referenceNode=this.getSelf(),k(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const dv=U(xr).setParameterLength(1,4).setName("texture"),_e=(o=Gg,e=null,t=null,s=null)=>{let i;return o&&o.isTextureNode===!0?(i=k(o.clone()),i.referenceNode=o.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=dv(o,e,t,s),i},xs=(...o)=>_e(...o).setSampler(!1);class pv extends St{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ut,this.minFilter=ut,this.generateMipmaps=!1,this.needsUpdate=!0}}const Fr=new ce;class Hg extends xr{static get type(){return"ViewportTextureNode"}constructor(e=nr,t=null,s=null){s===null&&(s=new pv,s.minFilter=ei),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=he.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Fr);const s=this.value;(s.image.width!==Fr.width||s.image.height!==Fr.height)&&(s.image.width=Fr.width,s.image.height=Fr.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Wg=U(Hg,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let ec=null;class fv extends Hg{static get type(){return"ViewportDepthTextureNode"}constructor(e=nr,t=null){ec===null&&(ec=new Is),super(e,t,ec)}}const mv=U(fv).setParameterLength(0,2);class kt extends re{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===kt.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===kt.DEPTH_BASE)s!==null&&(i=qg().assign(s));else if(t===kt.DEPTH)e.isPerspectiveCamera?i=gv(st.z,rn,on):i=uo(st.z,rn,on);else if(t===kt.LINEAR_DEPTH)if(s!==null)if(e.isPerspectiveCamera){const n=$g(s,rn,on);i=uo(n,rn,on)}else i=s;else i=uo(st.z,rn,on);return i}}kt.DEPTH_BASE="depthBase";kt.DEPTH="depth";kt.LINEAR_DEPTH="linearDepth";const uo=(o,e,t)=>o.add(e).div(e.sub(t)),gv=(o,e,t)=>e.add(o).mul(t).div(t.sub(e).mul(o)),$g=(o,e,t)=>e.mul(t).div(t.sub(e).mul(o).sub(t)),jg=(o,e,t)=>{e=e.max(1e-6).toVar();const s=ii(o.negate().div(e)),i=ii(t.div(e));return s.div(i)},qg=U(kt,kt.DEPTH_BASE),Yg=G(kt,kt.DEPTH),yv=U(kt,kt.LINEAR_DEPTH).setParameterLength(0,1);mv();Yg.assign=o=>qg(o);const tc=new N,xv=new N,_v=new Ht;class Mi{constructor(e=new N(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,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=tc.subVectors(s,t).cross(xv.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const 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){const s=e.delta(tc),i=this.normal.dot(s);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/i;return n<0||n>1?null:t.copy(e.start).addScaledVector(s,n)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<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){const s=t||_v.getNormalMatrix(e),i=this.coplanarPoint(tc).applyMatrix4(e),n=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(n),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)}}class fn extends pn{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Kt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new ge(0,0,e,t),this.scissorTest=!1,this.viewport=new ge(0,0,e,t);const i={width:e,height:t,depth:s.depth},n=new St(i);this.textures=[];const r=s.count;for(let a=0;a<r;a++)this.textures[a]=n.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:Kt,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 s=0;s<this.textures.length;s++)this.textures[s].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,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,n=this.textures.length;i<n;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,this.textures[i].isArrayTexture=this.textures[i].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,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const i=Object.assign({},e.textures[t].image);this.textures[t].source=new uu(i)}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}dispose(){this.dispatchEvent({type:"dispose"})}}new Mi;new N;new N;new N;new Ie;new N(0,0,-1);new ge;new N;new N;new ge;new ce;const bv=new fn;nr.flipX();bv.depthTexture=new Is(1,1);let Tv=0;class Gt extends pn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Tv++}),this.uuid=Qs(),this.name="",this.type="Material",this.blending=Js,this.side=Ks,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ja,this.blendDst=qa,this.blendEquation=bs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new ve(0,0,0),this.blendAlpha=0,this.depthFunc=Ya,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Fh,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=en,this.stencilZFail=en,this.stencilZPass=en,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(const t in e){const s=e[t];if(s===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(s.dispersion=this.dispersion),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapRotation!==void 0&&(s.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==Js&&(s.blending=this.blending),this.side!==Ks&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==ja&&(s.blendSrc=this.blendSrc),this.blendDst!==qa&&(s.blendDst=this.blendDst),this.blendEquation!==bs&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==Ya&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Fh&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==en&&(s.stencilFail=this.stencilFail),this.stencilZFail!==en&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==en&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function i(n){const r=[];for(const a in n){const l=n[a];delete l.metadata,r.push(l)}return r}if(t){const n=i(e.textures),r=i(e.images);n.length>0&&(s.textures=n),r.length>0&&(s.images=r)}return s}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;const t=e.clippingPlanes;let s=null;if(t!==null){const i=t.length;s=new Array(i);for(let n=0;n!==i;++n)s[n]=t[n].clone()}return this.clippingPlanes=s,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.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++}}const pp=new us,sc=new Ie,Sv=K(0).onReference(({material:o})=>o).onObjectUpdate(({material:o})=>o.refractionRatio),ic=K(1).onReference(({material:o})=>o).onObjectUpdate(function({material:o,scene:e}){return o.envMap?o.envMapIntensity:e.environmentIntensity}),Xg=K(new Ie).onReference(function(o){return o.material}).onObjectUpdate(function({material:o,scene:e}){const t=e.environment!==null&&o.envMap===null?e.environmentRotation:o.envMapRotation;return t?(pp.copy(t),sc.makeRotationFromEuler(pp)):sc.identity(),sc}),vv=je.negate().reflect(et),wv=je.negate().refract(et,Sv),Mv=vv.transformDirection(hi).toVar("reflectVector"),Cv=wv.transformDirection(hi).toVar("reflectVector");class vl extends St{constructor(e=[],t=yo,s,i,n,r,a,l,c,h){super(e,t,s,i,n,r,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}const Ev=new vl;class Av extends xr{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===yo?Mv:e.mapping===Xa?Cv:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),I(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return(e.renderer.coordinateSystem===Oi||!s.isRenderTargetTexture)&&(t=I(t.x.negate(),t.yz)),Xg.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const Rv=U(Av).setParameterLength(1,4).setName("cubeTexture"),vo=(o=Ev,e=null,t=null,s=null)=>{let i;return o&&o.isCubeTextureNode===!0?(i=k(o.clone()),i.referenceNode=o.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=Rv(o,e,t,s),i};class Nv extends Mo{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Bu extends re{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=he.OBJECT}element(e){return k(new Nv(this,k(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;this.count!==null?t=Bg(null,e,this.count):Array.isArray(this.getValueFromReference())?t=Os(null,e):e==="texture"?t=_e(null):e==="cubeTexture"?t=vo(null):t=K(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Be=(o,e,t)=>k(new Bu(o,e,t)),fp=(o,e,t,s)=>k(new Bu(o,e,s,t));class Pv extends Bu{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}}const Ei=(o,e,t=null)=>k(new Pv(o,e,t)),Zg=L(o=>(o.geometry.hasAttribute("tangent")===!1&&o.geometry.computeTangents(),Ii("tangent","vec4")))(),Iu=Zg.xyz.toVar("tangentLocal"),Qg=_l.mul(ne(Iu,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),Fv=L(([o,e],t)=>{let s=o.mul(Zg.w).xyz;return t.material.flatShading!==!0&&(s=ws(s,e)),s}).once(),Dv=Fv(zs.cross(Qg),"v_bitangentView").normalize().toVar("bitangentView"),eo=Ft(Qg,Dv,zs),Ov=(()=>{let o=ir.cross(je);return o=o.cross(ir).normalize(),o=Ve(o,et,tn.mul(Xs.oneMinus()).oneMinus().pow2().pow2()).normalize(),o})(),Bv=L(o=>{const{eye_pos:e,surf_norm:t,mapN:s,uv:i}=o,n=e.dFdx(),r=e.dFdy(),a=i.dFdx(),l=i.dFdy(),c=t,h=r.cross(c),u=c.cross(n),d=h.mul(a.x).add(u.mul(l.x)),p=h.mul(a.y).add(u.mul(l.y)),f=d.dot(d).max(p.dot(p)),m=Tl.mul(f.inverseSqrt());return Dt(d.mul(s.x,m),p.mul(s.y,m),c.mul(s.z)).normalize()});class Iv extends nt{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Di}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);s!==null&&(i=I(i.xy.mul(s),i.z));let n=null;return t===__?n=zg(i):t===Di&&(e.hasGeometryAttribute("tangent")===!0?n=eo.mul(i).normalize():n=Bv({eye_pos:st,surf_norm:zs,mapN:i,uv:Ao()})),n}}const mp=U(Iv).setParameterLength(1,2),Lv=L(({textureNode:o,bumpScale:e})=>{const t=i=>o.cache().context({getUV:n=>i(n.uvNode||Ao()),forceUVContext:!0}),s=B(t(i=>i));return H(B(t(i=>i.add(i.dFdx()))).sub(s),B(t(i=>i.add(i.dFdy()))).sub(s)).mul(e)}),Uv=L(o=>{const{surf_pos:e,surf_norm:t,dHdxy:s}=o,i=e.dFdx().normalize(),n=e.dFdy().normalize(),r=t,a=n.cross(r),l=r.cross(i),c=i.dot(a).mul(Tl),h=c.sign().mul(s.x.mul(a).add(s.y.mul(l)));return c.abs().mul(t).sub(h).normalize()});class kv extends nt{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=this.scaleNode!==null?this.scaleNode:1,t=Lv({textureNode:this.textureNode,bumpScale:e});return Uv({surf_pos:st,surf_norm:zs,dHdxy:t})}}const zv=U(kv).setParameterLength(1,2),gp=new Map;class D extends re{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=gp.get(e);return s===void 0&&(s=Ei(e,t),gp.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===D.COLOR){const n=t.color!==void 0?this.getColor(s):I();t.map&&t.map.isTexture===!0?i=n.mul(this.getTexture("map")):i=n}else if(s===D.OPACITY){const n=this.getFloat(s);t.alphaMap&&t.alphaMap.isTexture===!0?i=n.mul(this.getTexture("alpha")):i=n}else if(s===D.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=B(1);else if(s===D.SPECULAR_INTENSITY){const n=this.getFloat(s);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n}else if(s===D.SPECULAR_COLOR){const n=this.getColor(s);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=n.mul(this.getTexture(s).rgb):i=n}else if(s===D.ROUGHNESS){const n=this.getFloat(s);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.METALNESS){const n=this.getFloat(s);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=n.mul(this.getTexture(s).b):i=n}else if(s===D.EMISSIVE){const n=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(n);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=r.mul(this.getTexture(s)):i=r}else if(s===D.NORMAL)t.normalMap?(i=mp(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):t.bumpMap?i=zv(this.getTexture("bump").r,this.getFloat("bumpScale")):i=zs;else if(s===D.CLEARCOAT){const n=this.getFloat(s);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.CLEARCOAT_ROUGHNESS){const n=this.getFloat(s);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=mp(this.getTexture(s),this.getCache(s+"Scale","vec2")):i=zs;else if(s===D.SHEEN){const n=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=n.mul(this.getTexture("sheenColor").rgb):i=n}else if(s===D.SHEEN_ROUGHNESS){const n=this.getFloat(s);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n,i=i.clamp(.07,1)}else if(s===D.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const n=this.getTexture(s);i=xu(Dr.x,Dr.y,Dr.y.negate(),Dr.x).mul(n.rg.mul(2).sub(H(1)).normalize().mul(n.b))}else i=Dr;else if(s===D.IRIDESCENCE_THICKNESS){const n=Be("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Be("0","float",t.iridescenceThicknessRange);i=n.sub(r).mul(this.getTexture(s).g).add(r)}else i=n}else if(s===D.TRANSMISSION){const n=this.getFloat(s);t.transmissionMap?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.THICKNESS){const n=this.getFloat(s);t.thicknessMap?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.IOR)i=this.getFloat(s);else if(s===D.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===D.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===D.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):B(0);else{const n=this.getNodeType(e);i=this.getCache(s,n)}return i}}D.ALPHA_TEST="alphaTest";D.COLOR="color";D.OPACITY="opacity";D.SHININESS="shininess";D.SPECULAR="specular";D.SPECULAR_STRENGTH="specularStrength";D.SPECULAR_INTENSITY="specularIntensity";D.SPECULAR_COLOR="specularColor";D.REFLECTIVITY="reflectivity";D.ROUGHNESS="roughness";D.METALNESS="metalness";D.NORMAL="normal";D.CLEARCOAT="clearcoat";D.CLEARCOAT_ROUGHNESS="clearcoatRoughness";D.CLEARCOAT_NORMAL="clearcoatNormal";D.EMISSIVE="emissive";D.ROTATION="rotation";D.SHEEN="sheen";D.SHEEN_ROUGHNESS="sheenRoughness";D.ANISOTROPY="anisotropy";D.IRIDESCENCE="iridescence";D.IRIDESCENCE_IOR="iridescenceIOR";D.IRIDESCENCE_THICKNESS="iridescenceThickness";D.IOR="ior";D.TRANSMISSION="transmission";D.THICKNESS="thickness";D.ATTENUATION_DISTANCE="attenuationDistance";D.ATTENUATION_COLOR="attenuationColor";D.LINE_SCALE="scale";D.LINE_DASH_SIZE="dashSize";D.LINE_GAP_SIZE="gapSize";D.LINE_WIDTH="linewidth";D.LINE_DASH_OFFSET="dashOffset";D.POINT_SIZE="size";D.DISPERSION="dispersion";D.LIGHT_MAP="light";D.AO="ao";const Vv=G(D,D.ALPHA_TEST),Gv=G(D,D.COLOR),Hv=G(D,D.SHININESS),Wv=G(D,D.EMISSIVE),Kg=G(D,D.OPACITY),$v=G(D,D.SPECULAR),yp=G(D,D.SPECULAR_INTENSITY),jv=G(D,D.SPECULAR_COLOR),La=G(D,D.SPECULAR_STRENGTH),nc=G(D,D.REFLECTIVITY),qv=G(D,D.ROUGHNESS),Yv=G(D,D.METALNESS),Xv=G(D,D.NORMAL),Zv=G(D,D.CLEARCOAT),Qv=G(D,D.CLEARCOAT_ROUGHNESS),Kv=G(D,D.CLEARCOAT_NORMAL),Jv=G(D,D.ROTATION),ew=G(D,D.SHEEN),tw=G(D,D.SHEEN_ROUGHNESS),sw=G(D,D.ANISOTROPY),iw=G(D,D.IRIDESCENCE),nw=G(D,D.IRIDESCENCE_IOR),rw=G(D,D.IRIDESCENCE_THICKNESS),ow=G(D,D.TRANSMISSION),aw=G(D,D.THICKNESS),lw=G(D,D.IOR),cw=G(D,D.ATTENUATION_DISTANCE),hw=G(D,D.ATTENUATION_COLOR),uw=G(D,D.LINE_SCALE),dw=G(D,D.LINE_DASH_SIZE),pw=G(D,D.LINE_GAP_SIZE);D.LINE_WIDTH;const fw=G(D,D.LINE_DASH_OFFSET),mw=G(D,D.POINT_SIZE),gw=G(D,D.DISPERSION),Jg=G(D,D.LIGHT_MAP),yw=G(D,D.AO),Dr=K(new ce).onReference(function(o){return o.material}).onRenderUpdate(function({material:o}){this.value.set(o.anisotropy*Math.cos(o.anisotropyRotation),o.anisotropy*Math.sin(o.anisotropyRotation))}),ey=L(o=>o.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class xw extends Pg{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class _w extends ls{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}class bw extends re{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=he.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:s,instanceColor:i}=this;let{instanceMatrixNode:n,instanceColorNode:r}=this;if(n===null){if(t<=1e3)n=Bg(s.array,"mat4",Math.max(t,1)).element(Pu);else{const l=new xw(s.array,16,1);this.buffer=l;const c=s.usage===jn?lp:ap,h=[c(l,"vec4",16,0),c(l,"vec4",16,4),c(l,"vec4",16,8),c(l,"vec4",16,12)];n=sr(...h)}this.instanceMatrixNode=n}if(i&&r===null){const l=new _w(i.array,3),c=i.usage===jn?lp:ap;this.bufferColor=l,r=I(c(l,"vec3",3,0)),this.instanceColorNode=r}const a=n.mul(bt).xyz;if(bt.assign(a),e.hasGeometryAttribute("normal")){const l=nv(ks,n);ks.assign(l)}this.instanceColorNode!==null&&sl("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==jn&&this.buffer!==null&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==jn&&this.bufferColor!==null&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class Tw extends bw{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const Sw=U(Tw).setParameterLength(1);class vw extends re{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){this.batchingIdNode===null&&(e.getDrawIndex()===null?this.batchingIdNode=Pu:this.batchingIdNode=VS);const s=L(([f])=>{const m=ke(rr(xs(this.batchMesh._indirectTexture),0).x),y=ke(f).mod(m),g=ke(f).div(m);return xs(this.batchMesh._indirectTexture,qs(y,g)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(ke(this.batchingIdNode)),i=this.batchMesh._matricesTexture,n=ke(rr(xs(i),0).x),r=B(s).mul(4).toInt().toVar(),a=r.mod(n),l=r.div(n),c=sr(xs(i,qs(a,l)),xs(i,qs(a.add(1),l)),xs(i,qs(a.add(2),l)),xs(i,qs(a.add(3),l))),h=this.batchMesh._colorsTexture;if(h!==null){const m=L(([y])=>{const g=ke(rr(xs(h),0).x),_=y,b=_.mod(g),T=_.div(g);return xs(h,qs(b,T)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(s);sl("vec3","vBatchColor").assign(m)}const u=Ft(c);bt.assign(c.mul(bt));const d=ks.div(I(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),p=u.mul(d).xyz;ks.assign(p),e.hasGeometryAttribute("tangent")&&Iu.mulAssign(u)}}const ww=U(vw).setParameterLength(1),xp=new WeakMap;class Mw extends re{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=he.OBJECT,this.skinIndexNode=Ii("skinIndex","uvec4"),this.skinWeightNode=Ii("skinWeight","vec4"),this.bindMatrixNode=Be("bindMatrix","mat4"),this.bindMatrixInverseNode=Be("bindMatrixInverse","mat4"),this.boneMatricesNode=fp("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=bt,this.toPositionNode=bt,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,a=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w),u=n.mul(t),d=Dt(a.mul(i.x).mul(u),l.mul(i.y).mul(u),c.mul(i.z).mul(u),h.mul(i.w).mul(u));return r.mul(d).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=ks){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,a=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w);let u=Dt(i.x.mul(a),i.y.mul(l),i.z.mul(c),i.w.mul(h));return u=r.mul(u).mul(n),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=fp("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dp)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||qm(e.object).useVelocity===!0}setup(e){this.needsPreviousBoneMatrices(e)&&dp.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const s=this.getSkinnedNormal();ks.assign(s),e.hasGeometryAttribute("tangent")&&Iu.assign(s)}return t}generate(e,t){if(t!=="void")return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;xp.get(t)!==e.frameId&&(xp.set(t,e.frameId),this.previousBoneMatricesNode!==null&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const Cw=o=>k(new Mw(o));class Ew extends St{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=ut,this.minFilter=ut,this.wrapR=Ri,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}const rc=new WeakMap,jt=new ge,_p=L(({bufferMap:o,influence:e,stride:t,width:s,depth:i,offset:n})=>{const r=ke(zS).mul(t).add(n),a=r.div(s),l=r.sub(a.mul(s));return xs(o,qs(l,a)).depth(i).xyz.mul(e)});function Aw(o){const e=o.morphAttributes.position!==void 0,t=o.morphAttributes.normal!==void 0,s=o.morphAttributes.color!==void 0,i=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,n=i!==void 0?i.length:0;let r=rc.get(o);if(r===void 0||r.count!==n){let g=function(){m.dispose(),rc.delete(o),o.removeEventListener("dispose",g)};r!==void 0&&r.texture.dispose();const a=o.morphAttributes.position||[],l=o.morphAttributes.normal||[],c=o.morphAttributes.color||[];let h=0;e===!0&&(h=1),t===!0&&(h=2),s===!0&&(h=3);let u=o.attributes.position.count*h,d=1;const p=4096;u>p&&(d=Math.ceil(u/p),u=p);const f=new Float32Array(u*d*4*n),m=new Ew(f,u,d,n);m.type=Qt,m.needsUpdate=!0;const y=h*4;for(let _=0;_<n;_++){const b=a[_],T=l[_],S=c[_],C=u*d*4*_;for(let w=0;w<b.count;w++){const R=w*y;e===!0&&(jt.fromBufferAttribute(b,w),f[C+R+0]=jt.x,f[C+R+1]=jt.y,f[C+R+2]=jt.z,f[C+R+3]=0),t===!0&&(jt.fromBufferAttribute(T,w),f[C+R+4]=jt.x,f[C+R+5]=jt.y,f[C+R+6]=jt.z,f[C+R+7]=0),s===!0&&(jt.fromBufferAttribute(S,w),f[C+R+8]=jt.x,f[C+R+9]=jt.y,f[C+R+10]=jt.z,f[C+R+11]=S.itemSize===4?jt.w:1)}}r={count:n,texture:m,stride:h,size:new ce(u,d)},rc.set(o,r),o.addEventListener("dispose",g)}return r}class Rw extends re{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=K(1),this.updateType=he.OBJECT}setup(e){const{geometry:t}=e,s=t.morphAttributes.position!==void 0,i=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,n=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,r=n!==void 0?n.length:0,{texture:a,stride:l,size:c}=Aw(t);s===!0&&bt.mulAssign(this.morphBaseInfluence),i===!0&&ks.mulAssign(this.morphBaseInfluence);const h=ke(c.width);Ts(r,({i:u})=>{const d=B(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?d.assign(xs(this.mesh.morphTexture,qs(ke(u).add(1),ke(Pu))).r):d.assign(Be("morphTargetInfluences","float").element(u).toVar()),Ze(d.notEqual(0),()=>{s===!0&&bt.addAssign(_p({bufferMap:a,influence:d,stride:l,width:h,depth:u,offset:ke(0)})),i===!0&&ks.addAssign(_p({bufferMap:a,influence:d,stride:l,width:h,depth:u,offset:ke(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((t,s)=>t+s,0)}}const Nw=U(Rw).setParameterLength(1);class _r extends re{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Pw extends _r{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Fw extends Ag{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s=I().toVar("directDiffuse"),i=I().toVar("directSpecular"),n=I().toVar("indirectDiffuse"),r=I().toVar("indirectSpecular"),a={directDiffuse:s,directSpecular:i,indirectDiffuse:n,indirectSpecular:r};return{radiance:I().toVar("radiance"),irradiance:I().toVar("irradiance"),iblIrradiance:I().toVar("iblIrradiance"),ambientOcclusion:B(1).toVar("ambientOcclusion"),reflectedLight:a,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Dw=U(Fw);class Ow extends _r{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}class cs extends re{static get type(){return"ClippingNode"}constructor(e=cs.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===cs.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===cs.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return L(()=>{const s=B().toVar("distanceToPlane"),i=B().toVar("distanceToGradient"),n=B(1).toVar("clipOpacity"),r=t.length;if(this.hardwareClipping===!1&&r>0){const l=Os(t);Ts(r,({i:c})=>{const h=l.element(c);s.assign(st.dot(h.xyz).negate().add(h.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Bi(i.negate(),i,s))})}const a=e.length;if(a>0){const l=Os(e),c=B(1).toVar("intersectionClipOpacity");Ts(a,({i:h})=>{const u=l.element(h);s.assign(st.dot(u.xyz).negate().add(u.w)),i.assign(s.fwidth().div(2)),c.mulAssign(Bi(i.negate(),i,s).oneMinus())}),n.mulAssign(c.oneMinus())}Se.a.mulAssign(n),Se.a.equal(0).discard()})()}setupDefault(e,t){return L(()=>{const s=t.length;if(this.hardwareClipping===!1&&s>0){const n=Os(t);Ts(s,({i:r})=>{const a=n.element(r);st.dot(a.xyz).greaterThan(a.w).discard()})}const i=e.length;if(i>0){const n=Os(e),r=yu(!0).toVar("clipped");Ts(i,({i:a})=>{const l=n.element(a);r.assign(st.dot(l.xyz).greaterThan(l.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),L(()=>{const i=Os(e),n=xl(t.getClipDistance());Ts(s,({i:r})=>{const a=i.element(r),l=st.dot(a.xyz).sub(a.w).negate();n.element(r).assign(l)})})()}}cs.ALPHA_TO_COVERAGE="alphaToCoverage";cs.DEFAULT="default";cs.HARDWARE="hardware";const Bw=()=>k(new cs),Iw=()=>k(new cs(cs.ALPHA_TO_COVERAGE)),Lw=()=>k(new cs(cs.HARDWARE)),Uw=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class kw{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=Uw,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:s,material:i,object:n}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:n.matrixWorld.clone()},n.center&&(t.center=n.center.clone()),n.morphTargetInfluences&&(t.morphTargetInfluences=n.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:a}=e.context;t.bufferWidth=r,t.bufferHeight=a}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={version:i.version}}return t}containsNode(e){const t=e.material;for(const s in t)if(t[s]&&t[s].isNode)return!0;return e.renderer.overrideNodes.modelViewMatrix!==null||e.renderer.overrideNodes.modelNormalViewMatrix!==null}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];i!=null&&(typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e){const{object:t,material:s,geometry:i}=e,n=this.getRenderObjectData(e);if(n.worldMatrix.equals(t.matrixWorld)!==!0)return n.worldMatrix.copy(t.matrixWorld),!1;const r=n.material;for(const m in r){const y=r[m],g=s[m];if(y.equals!==void 0){if(y.equals(g)===!1)return y.copy(g),!1}else if(g.isTexture===!0){if(y.id!==g.id||y.version!==g.version)return y.id=g.id,y.version=g.version,!1}else if(y!==g)return r[m]=g,!1}if(r.transmission>0){const{width:m,height:y}=e.context;if(n.bufferWidth!==m||n.bufferHeight!==y)return n.bufferWidth=m,n.bufferHeight=y,!1}const a=n.geometry,l=i.attributes,c=a.attributes,h=Object.keys(c),u=Object.keys(l);if(a.id!==i.id)return a.id=i.id,!1;if(h.length!==u.length)return n.geometry.attributes=this.getAttributesData(l),!1;for(const m of h){const y=c[m],g=l[m];if(g===void 0)return delete c[m],!1;if(y.version!==g.version)return y.version=g.version,!1}const d=i.index,p=a.indexVersion,f=d?d.version:null;if(p!==f)return a.indexVersion=f,!1;if(a.drawRange.start!==i.drawRange.start||a.drawRange.count!==i.drawRange.count)return a.drawRange.start=i.drawRange.start,a.drawRange.count=i.drawRange.count,!1;if(n.morphTargetInfluences){let m=!1;for(let y=0;y<n.morphTargetInfluences.length;y++)n.morphTargetInfluences[y]!==t.morphTargetInfluences[y]&&(m=!0);if(m)return!0}return n.center&&n.center.equals(t.center)===!1?(n.center.copy(t.center),!0):(e.bundle!==null&&(n.version=e.bundle.version),!0)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=e.object.static===!0,n=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;return i||n?!1:this.equals(e)!==!0}}const zw=.05,bp=L(([o])=>Ui(fe(1e4,_s(fe(17,o.x).add(fe(.1,o.y)))).mul(Dt(.1,ns(_s(fe(13,o.y).add(o.x))))))),Tp=L(([o])=>bp(H(bp(o.xy),o.z))),Vw=L(([o])=>{const e=vt(ni(bg(o.xyz)),ni(Tg(o.xyz))),t=B(1).div(B(zw).mul(e)).toVar("pixScale"),s=H(bo(un(ii(t))),bo(vu(ii(t)))),i=H(Tp(un(s.x.mul(o.xyz))),Tp(un(s.y.mul(o.xyz)))),n=Ui(ii(t)),r=Dt(fe(n.oneMinus(),i.x),fe(n,i.y)),a=dr(n,n.oneMinus()),l=I(r.mul(r).div(fe(2,a).mul(At(1,a))),r.sub(fe(.5,a)).div(At(1,a)),At(1,At(1,r).mul(At(1,r)).div(fe(2,a).mul(At(1,a))))),c=r.lessThan(a.oneMinus()).select(r.lessThan(a).select(l.x,l.y),l.z);return ai(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Gw extends Dg{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e),s=e.hasGeometryAttribute(t);let i;return s===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new ge(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Hw=(o=0)=>k(new Gw(o));class it extends Gt{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+$m(this)}build(e){this.setup(e)}setupObserver(e){return new kw(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),n=this.vertexNode||i;e.stack.outputNode=n,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let r;const a=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(s!==null?s.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupVariants(e);const l=this.setupLighting(e);a!==null&&e.stack.add(a);const c=ne(l,Se.a).max(0);r=this.setupOutput(e,c),co.assign(r);const h=this.outputNode!==null;if(h&&(r=this.outputNode),s!==null){const u=t.getMRT(),d=this.mrtNode;u!==null?(h&&co.assign(r),r=u,d!==null&&(r=u.merge(d))):d!==null&&(r=d)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=ne(l)),r=this.setupOutput(e,l)}e.stack.outputNode=r,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const n=e.renderer.samples;this.alphaToCoverage&&n>1?i=Iw():e.stack.add(Bw())}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.add(Lw()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(i===null){const n=t.getMRT();n&&n.has("depth")?i=n.get("depth"):t.logarithmicDepthBuffer===!0&&(s.isPerspectiveCamera?i=jg(st.z,rn,on):i=uo(st.z,rn,on))}i!==null&&Yg.assign(i).toStack()}setupPositionView(){return _l.mul(bt).xyz}setupModelViewProjection(){return Fu.mul(st)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),ey}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Nw(t).toStack(),t.isSkinnedMesh===!0&&Cw(t).toStack(),this.displacementMap){const i=Ei("displacementMap","texture"),n=Ei("displacementScale","float"),r=Ei("displacementBias","float");bt.addAssign(ks.normalize().mul(i.x.mul(n).add(r)))}return t.isBatchedMesh&&ww(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&Sw(t).toStack(),this.positionNode!==null&&bt.assign(NS(this.positionNode,"POSITION")),bt}setupDiffuseColor({object:e,geometry:t}){this.maskNode!==null&&yu(this.maskNode).not().discard();let s=this.colorNode?ne(this.colorNode):Gv;this.vertexColors===!0&&t.hasAttribute("color")&&(s=s.mul(Hw())),e.instanceColor&&(s=sl("vec3","vInstanceColor").mul(s)),e.isBatchedMesh&&e._colorsTexture&&(s=sl("vec3","vBatchColor").mul(s)),Se.assign(s);const i=this.opacityNode?B(this.opacityNode):Kg;Se.a.assign(Se.a.mul(i));let n=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(n=this.alphaTestNode!==null?B(this.alphaTestNode):Vv,Se.a.lessThanEqual(n).discard()),this.alphaHash===!0&&Se.a.lessThan(Vw(bt)).discard(),this.transparent===!1&&this.blending===Js&&this.alphaToCoverage===!1?Se.a.assign(1):n===null&&Se.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return this.lights===!0?I(0):Se.rgb}setupNormal(){return this.normalNode?I(this.normalNode):Xv}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ei("envMap","cubeTexture"):Ei("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Ow(Jg)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),this.aoNode!==null||e.material.aoMap){const r=this.aoNode!==null?this.aoNode:yw;t.push(new Pw(r))}let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:n}=this,a=this.lights===!0||this.lightsNode!==null?this.setupLights(e):null;let l=this.setupOutgoingLight(e);if(a&&a.getScope().hasLights){const c=this.setupLightingModel(e)||null;l=Dw(a,c,s,i)}else s!==null&&(l=I(i!==null?Ve(l,s,i):s));return(n&&n.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(rp.assign(I(n||Wv)),l=l.add(rp)),l}setupFog(e,t){const s=e.fogNode;return s&&(co.assign(t),t=ne(s)),t}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),t}setDefaultValues(e){for(const s in e){const i=e[s];this[s]===void 0&&(this[s]=i,i&&i.clone&&(this[s]=i.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const s in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,s)===void 0&&t[s].get!==void 0&&Object.defineProperty(this.constructor.prototype,s,t[s])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const s=Gt.prototype.toJSON.call(this,e),i=Ja(this);s.inputNodes={};for(const{property:r,childNode:a}of i)s.inputNodes[r]=a.toJSON(e).uuid;function n(r){const a=[];for(const l in r){const c=r[l];delete c.metadata,a.push(c)}return a}if(t){const r=n(e.textures),a=n(e.images),l=n(e.nodes);r.length>0&&(s.textures=r),a.length>0&&(s.images=a),l.length>0&&(s.nodes=l)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}let Ww=0;const es=new Ie,oc=new dt,Nn=new N,qt=new Eo,Or=new Eo,pt=new N;class ui extends pn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Ww++}),this.uuid=Qs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,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(Hm(e)?Xm:Ym)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,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,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(s!==void 0){const n=new Ht().getNormalMatrix(e);s.applyNormalMatrix(n),s.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return es.makeRotationFromQuaternion(e),this.applyMatrix4(es),this}rotateX(e){return es.makeRotationX(e),this.applyMatrix4(es),this}rotateY(e){return es.makeRotationY(e),this.applyMatrix4(es),this}rotateZ(e){return es.makeRotationZ(e),this.applyMatrix4(es),this}translate(e,t,s){return es.makeTranslation(e,t,s),this.applyMatrix4(es),this}scale(e,t,s){return es.makeScale(e,t,s),this.applyMatrix4(es),this}lookAt(e){return oc.lookAt(e),oc.updateMatrix(),this.applyMatrix4(oc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Nn).negate(),this.translate(Nn.x,Nn.y,Nn.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const s=[];for(let i=0,n=e.length;i<n;i++){const r=e[i];s.push(r.x,r.y,r.z||0)}this.setAttribute("position",new Pt(s,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.count&&console.warn("THREE.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 Eo);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let s=0,i=t.length;s<i;s++){const n=t[s];qt.setFromBufferAttribute(n),this.morphTargetsRelative?(pt.addVectors(this.boundingBox.min,qt.min),this.boundingBox.expandByPoint(pt),pt.addVectors(this.boundingBox.max,qt.max),this.boundingBox.expandByPoint(pt)):(this.boundingBox.expandByPoint(qt.min),this.boundingBox.expandByPoint(qt.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.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 yl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new N,1/0);return}if(e){const s=this.boundingSphere.center;if(qt.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n<r;n++){const a=t[n];Or.setFromBufferAttribute(a),this.morphTargetsRelative?(pt.addVectors(qt.min,Or.min),qt.expandByPoint(pt),pt.addVectors(qt.max,Or.max),qt.expandByPoint(pt)):(qt.expandByPoint(Or.min),qt.expandByPoint(Or.max))}qt.getCenter(s);let i=0;for(let n=0,r=e.count;n<r;n++)pt.fromBufferAttribute(e,n),i=Math.max(i,s.distanceToSquared(pt));if(t)for(let n=0,r=t.length;n<r;n++){const a=t[n],l=this.morphTargetsRelative;for(let c=0,h=a.count;c<h;c++)pt.fromBufferAttribute(a,c),l&&(Nn.fromBufferAttribute(e,c),pt.add(Nn)),i=Math.max(i,s.distanceToSquared(pt))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const s=t.position,i=t.normal,n=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ls(new Float32Array(4*s.count),4));const r=this.getAttribute("tangent"),a=[],l=[];for(let R=0;R<s.count;R++)a[R]=new N,l[R]=new N;const c=new N,h=new N,u=new N,d=new ce,p=new ce,f=new ce,m=new N,y=new N;function g(R,P,z){c.fromBufferAttribute(s,R),h.fromBufferAttribute(s,P),u.fromBufferAttribute(s,z),d.fromBufferAttribute(n,R),p.fromBufferAttribute(n,P),f.fromBufferAttribute(n,z),h.sub(c),u.sub(c),p.sub(d),f.sub(d);const $=1/(p.x*f.y-f.x*p.y);isFinite($)&&(m.copy(h).multiplyScalar(f.y).addScaledVector(u,-p.y).multiplyScalar($),y.copy(u).multiplyScalar(p.x).addScaledVector(h,-f.x).multiplyScalar($),a[R].add(m),a[P].add(m),a[z].add(m),l[R].add(y),l[P].add(y),l[z].add(y))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)g(e.getX(j+0),e.getX(j+1),e.getX(j+2))}const b=new N,T=new N,S=new N,C=new N;function w(R){S.fromBufferAttribute(i,R),C.copy(S);const P=a[R];b.copy(P),b.sub(S.multiplyScalar(S.dot(P))).normalize(),T.crossVectors(C,P);const $=T.dot(l[R])<0?-1:1;r.setXYZW(R,b.x,b.y,b.z,$)}for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)w(e.getX(j+0)),w(e.getX(j+1)),w(e.getX(j+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let s=this.getAttribute("normal");if(s===void 0)s=new ls(new Float32Array(t.count*3),3),this.setAttribute("normal",s);else for(let d=0,p=s.count;d<p;d++)s.setXYZ(d,0,0,0);const i=new N,n=new N,r=new N,a=new N,l=new N,c=new N,h=new N,u=new N;if(e)for(let d=0,p=e.count;d<p;d+=3){const f=e.getX(d+0),m=e.getX(d+1),y=e.getX(d+2);i.fromBufferAttribute(t,f),n.fromBufferAttribute(t,m),r.fromBufferAttribute(t,y),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),a.fromBufferAttribute(s,f),l.fromBufferAttribute(s,m),c.fromBufferAttribute(s,y),a.add(h),l.add(h),c.add(h),s.setXYZ(f,a.x,a.y,a.z),s.setXYZ(m,l.x,l.y,l.z),s.setXYZ(y,c.x,c.y,c.z)}else for(let d=0,p=t.count;d<p;d+=3)i.fromBufferAttribute(t,d+0),n.fromBufferAttribute(t,d+1),r.fromBufferAttribute(t,d+2),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),s.setXYZ(d+0,h.x,h.y,h.z),s.setXYZ(d+1,h.x,h.y,h.z),s.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)pt.fromBufferAttribute(e,t),pt.normalize(),e.setXYZ(t,pt.x,pt.y,pt.z)}toNonIndexed(){function e(a,l){const c=a.array,h=a.itemSize,u=a.normalized,d=new c.constructor(l.length*h);let p=0,f=0;for(let m=0,y=l.length;m<y;m++){a.isInterleavedBufferAttribute?p=l[m]*a.data.stride+a.offset:p=l[m]*h;for(let g=0;g<h;g++)d[f++]=c[p++]}return new ls(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ui,s=this.index.array,i=this.attributes;for(const a in i){const l=i[a],c=e(l,s);t.setAttribute(a,c)}const n=this.morphAttributes;for(const a in n){const l=[],c=n[a];for(let h=0,u=c.length;h<u;h++){const d=c[h],p=e(d,s);l.push(p)}t.morphAttributes[a]=l}t.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,l=r.length;a<l;a++){const c=r[a];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const 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){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const l in s){const c=s[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let n=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u];h.push(p.toJSON(e.data))}h.length>0&&(i[l]=h,n=!0)}n&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.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;const t={};this.name=e.name;const s=e.index;s!==null&&this.setIndex(s.clone());const i=e.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(t))}const n=e.morphAttributes;for(const c in n){const h=[],u=n[c];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const r=e.groups;for(let c=0,h=r.length;c<h;c++){const u=r[c];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Ws=new N,ac=new N,$o=new N,gi=new N,lc=new N,jo=new N,cc=new N;class $w{constructor(e=new N,t=new N(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,Ws)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ws.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ws.copy(this.origin).addScaledVector(this.direction,t),Ws.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){ac.copy(e).add(t).multiplyScalar(.5),$o.copy(t).sub(e).normalize(),gi.copy(this.origin).sub(ac);const n=e.distanceTo(t)*.5,r=-this.direction.dot($o),a=gi.dot(this.direction),l=-gi.dot($o),c=gi.lengthSq(),h=Math.abs(1-r*r);let u,d,p,f;if(h>0)if(u=r*l-a,d=r*a-l,f=n*h,u>=0)if(d>=-f)if(d<=f){const m=1/h;u*=m,d*=m,p=u*(u+r*d+2*a)+d*(r*u+d+2*l)+c}else d=n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;else d=-n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;else d<=-f?(u=Math.max(0,-(-r*n+a)),d=u>0?-n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c):d<=f?(u=0,d=Math.min(Math.max(-n,-l),n),p=d*(d+2*l)+c):(u=Math.max(0,-(r*n+a)),d=u>0?n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c);else d=r>0?-n:n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(ac).addScaledVector($o,d),p}intersectSphere(e,t){Ws.subVectors(e.center,this.origin);const s=Ws.dot(this.direction),i=Ws.dot(Ws)-s*s,n=e.radius*e.radius;if(i>n)return null;const r=Math.sqrt(n-i),a=s-r,l=s+r;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return s===null?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,n,r,a,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(s=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(s=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),h>=0?(n=(e.min.y-d.y)*h,r=(e.max.y-d.y)*h):(n=(e.max.y-d.y)*h,r=(e.min.y-d.y)*h),s>r||n>i||((n>s||isNaN(s))&&(s=n),(r<i||isNaN(i))&&(i=r),u>=0?(a=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),s>l||a>i)||((a>s||s!==s)&&(s=a),(l<i||i!==i)&&(i=l),i<0)?null:this.at(s>=0?s:i,t)}intersectsBox(e){return this.intersectBox(e,Ws)!==null}intersectTriangle(e,t,s,i,n){lc.subVectors(t,e),jo.subVectors(s,e),cc.crossVectors(lc,jo);let r=this.direction.dot(cc),a;if(r>0){if(i)return null;a=1}else if(r<0)a=-1,r=-r;else return null;gi.subVectors(this.origin,e);const l=a*this.direction.dot(jo.crossVectors(gi,jo));if(l<0)return null;const c=a*this.direction.dot(lc.cross(gi));if(c<0||l+c>r)return null;const h=-a*gi.dot(cc);return h<0?null:this.at(h/r,n)}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)}}const ms=new N,$s=new N,hc=new N,js=new N,Pn=new N,Fn=new N,Sp=new N,uc=new N,dc=new N,pc=new N,fc=new ge,mc=new ge,gc=new ge;class Ss{constructor(e=new N,t=new N,s=new N){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),ms.subVectors(e,t),i.cross(ms);const n=i.lengthSq();return n>0?i.multiplyScalar(1/Math.sqrt(n)):i.set(0,0,0)}static getBarycoord(e,t,s,i,n){ms.subVectors(i,t),$s.subVectors(s,t),hc.subVectors(e,t);const r=ms.dot(ms),a=ms.dot($s),l=ms.dot(hc),c=$s.dot($s),h=$s.dot(hc),u=r*c-a*a;if(u===0)return n.set(0,0,0),null;const d=1/u,p=(c*l-a*h)*d,f=(r*h-a*l)*d;return n.set(1-p-f,f,p)}static containsPoint(e,t,s,i){return this.getBarycoord(e,t,s,i,js)===null?!1:js.x>=0&&js.y>=0&&js.x+js.y<=1}static getInterpolation(e,t,s,i,n,r,a,l){return this.getBarycoord(e,t,s,i,js)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(n,js.x),l.addScaledVector(r,js.y),l.addScaledVector(a,js.z),l)}static getInterpolatedAttribute(e,t,s,i,n,r){return fc.setScalar(0),mc.setScalar(0),gc.setScalar(0),fc.fromBufferAttribute(e,t),mc.fromBufferAttribute(e,s),gc.fromBufferAttribute(e,i),r.setScalar(0),r.addScaledVector(fc,n.x),r.addScaledVector(mc,n.y),r.addScaledVector(gc,n.z),r}static isFrontFacing(e,t,s,i){return ms.subVectors(s,t),$s.subVectors(e,t),ms.cross($s).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),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 ms.subVectors(this.c,this.b),$s.subVectors(this.a,this.b),ms.cross($s).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ss.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ss.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,n){return Ss.getInterpolation(e,this.a,this.b,this.c,t,s,i,n)}containsPoint(e){return Ss.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ss.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,n=this.c;let r,a;Pn.subVectors(i,s),Fn.subVectors(n,s),uc.subVectors(e,s);const l=Pn.dot(uc),c=Fn.dot(uc);if(l<=0&&c<=0)return t.copy(s);dc.subVectors(e,i);const h=Pn.dot(dc),u=Fn.dot(dc);if(h>=0&&u<=h)return t.copy(i);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return r=l/(l-h),t.copy(s).addScaledVector(Pn,r);pc.subVectors(e,n);const p=Pn.dot(pc),f=Fn.dot(pc);if(f>=0&&p<=f)return t.copy(n);const m=p*c-l*f;if(m<=0&&c>=0&&f<=0)return a=c/(c-f),t.copy(s).addScaledVector(Fn,a);const y=h*f-p*u;if(y<=0&&u-h>=0&&p-f>=0)return Sp.subVectors(n,i),a=(u-h)/(u-h+(p-f)),t.copy(i).addScaledVector(Sp,a);const g=1/(y+m+d);return r=m*g,a=d*g,t.copy(s).addScaledVector(Pn,r).addScaledVector(Fn,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ai extends Gt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ve(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 us,this.combine=hl,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}}const vp=new Ie,Wi=new $w,qo=new yl,wp=new N,Yo=new N,Xo=new N,Zo=new N,yc=new N,Qo=new N,Mp=new N,Ko=new N;class li extends dt{constructor(e=new ui,t=new Ai){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(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let n=0,r=i.length;n<r;n++){const a=i[n].name||String(n);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=n}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,n=s.morphAttributes.position,r=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(n&&a){Qo.set(0,0,0);for(let l=0,c=n.length;l<c;l++){const h=a[l],u=n[l];h!==0&&(yc.fromBufferAttribute(u,e),r?Qo.addScaledVector(yc,h):Qo.addScaledVector(yc.sub(t),h))}t.add(Qo)}return t}raycast(e,t){const s=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(s.boundingSphere===null&&s.computeBoundingSphere(),qo.copy(s.boundingSphere),qo.applyMatrix4(n),Wi.copy(e.ray).recast(e.near),!(qo.containsPoint(Wi.origin)===!1&&(Wi.intersectSphere(qo,wp)===null||Wi.origin.distanceToSquared(wp)>(e.far-e.near)**2))&&(vp.copy(n).invert(),Wi.copy(e.ray).applyMatrix4(vp),!(s.boundingBox!==null&&Wi.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Wi)))}_computeIntersections(e,t,s){let i;const n=this.geometry,r=this.material,a=n.index,l=n.attributes.position,c=n.attributes.uv,h=n.attributes.uv1,u=n.attributes.normal,d=n.groups,p=n.drawRange;if(a!==null)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const y=d[f],g=r[y.materialIndex],_=Math.max(y.start,p.start),b=Math.min(a.count,Math.min(y.start+y.count,p.start+p.count));for(let T=_,S=b;T<S;T+=3){const C=a.getX(T),w=a.getX(T+1),R=a.getX(T+2);i=Jo(this,g,e,s,c,h,u,C,w,R),i&&(i.faceIndex=Math.floor(T/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(a.count,p.start+p.count);for(let y=f,g=m;y<g;y+=3){const _=a.getX(y),b=a.getX(y+1),T=a.getX(y+2);i=Jo(this,r,e,s,c,h,u,_,b,T),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const y=d[f],g=r[y.materialIndex],_=Math.max(y.start,p.start),b=Math.min(l.count,Math.min(y.start+y.count,p.start+p.count));for(let T=_,S=b;T<S;T+=3){const C=T,w=T+1,R=T+2;i=Jo(this,g,e,s,c,h,u,C,w,R),i&&(i.faceIndex=Math.floor(T/3),i.face.materialIndex=y.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(l.count,p.start+p.count);for(let y=f,g=m;y<g;y+=3){const _=y,b=y+1,T=y+2;i=Jo(this,r,e,s,c,h,u,_,b,T),i&&(i.faceIndex=Math.floor(y/3),t.push(i))}}}}function jw(o,e,t,s,i,n,r,a){let l;if(e.side===Vt?l=s.intersectTriangle(r,n,i,!0,a):l=s.intersectTriangle(i,n,r,e.side===Ks,a),l===null)return null;Ko.copy(a),Ko.applyMatrix4(o.matrixWorld);const c=t.ray.origin.distanceTo(Ko);return c<t.near||c>t.far?null:{distance:c,point:Ko.clone(),object:o}}function Jo(o,e,t,s,i,n,r,a,l,c){o.getVertexPosition(a,Yo),o.getVertexPosition(l,Xo),o.getVertexPosition(c,Zo);const h=jw(o,e,t,s,Yo,Xo,Zo,Mp);if(h){const u=new N;Ss.getBarycoord(Mp,Yo,Xo,Zo,u),i&&(h.uv=Ss.getInterpolatedAttribute(i,a,l,c,u,new ce)),n&&(h.uv1=Ss.getInterpolatedAttribute(n,a,l,c,u,new ce)),r&&(h.normal=Ss.getInterpolatedAttribute(r,a,l,c,u,new N),h.normal.dot(s.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:l,c,normal:new N,materialIndex:0};Ss.getNormal(Yo,Xo,Zo,d.normal),h.face=d,h.barycoord=u}return h}class Lu extends hu{constructor(e=-1,t=1,s=1,i=-1,n=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=n,this.far=r,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,n,r){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let n=s-e,r=s+e,a=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=c*this.view.offsetX,r=n+c*this.view.width,a-=h*this.view.offsetY,l=a-h*this.view.height}this.projectionMatrix.makeOrthographic(n,r,a,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const xc=new Lu(-1,1,1,-1,0,1);class qw extends ui{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Pt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Pt(t,2))}}const Yw=new qw;class Uu extends li{constructor(e=null){super(Yw,e),this.camera=xc,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,xc)}render(e){e.render(this,xc)}}const wl=1/6,ty=o=>fe(wl,fe(o,fe(o,o.negate().add(3)).sub(3)).add(1)),zh=o=>fe(wl,fe(o,fe(o,fe(3,o).sub(6))).add(4)),sy=o=>fe(wl,fe(o,fe(o,fe(-3,o).add(3)).add(3)).add(1)),Vh=o=>fe(wl,gl(o,3)),Cp=o=>ty(o).add(zh(o)),Ep=o=>sy(o).add(Vh(o)),Ap=o=>Dt(-1,zh(o).div(ty(o).add(zh(o)))),Rp=o=>Dt(1,Vh(o).div(sy(o).add(Vh(o)))),Np=(o,e,t)=>{const s=o.uvNode,i=fe(s,e.zw).add(.5),n=un(i),r=Ui(i),a=Cp(r.x),l=Ep(r.x),c=Ap(r.x),h=Rp(r.x),u=Ap(r.y),d=Rp(r.y),p=H(n.x.add(c),n.y.add(u)).sub(.5).mul(e.xy),f=H(n.x.add(h),n.y.add(u)).sub(.5).mul(e.xy),m=H(n.x.add(c),n.y.add(d)).sub(.5).mul(e.xy),y=H(n.x.add(h),n.y.add(d)).sub(.5).mul(e.xy),g=Cp(r.y).mul(Dt(a.mul(o.sample(p).level(t)),l.mul(o.sample(f).level(t)))),_=Ep(r.y).mul(Dt(a.mul(o.sample(m).level(t)),l.mul(o.sample(y).level(t))));return g.add(_)},Xw=L(([o,e=B(3)])=>{const t=H(o.size(ke(e))),s=H(o.size(ke(e.add(1)))),i=Us(1,t),n=Us(1,s),r=Np(o,ne(i,t),un(e)),a=Np(o,ne(n,s),vu(e));return Ui(e).mix(r,a)}),Br=new us,_c=new Ie;class zt extends re{static get type(){return"SceneNode"}constructor(e=zt.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=this.scene!==null?this.scene:e.scene;let i;return t===zt.BACKGROUND_BLURRINESS?i=Be("backgroundBlurriness","float",s):t===zt.BACKGROUND_INTENSITY?i=Be("backgroundIntensity","float",s):t===zt.BACKGROUND_ROTATION?i=K("mat4").label("backgroundRotation").setGroup(Q).onRenderUpdate(()=>{const n=s.background;return n!==null&&n.isTexture&&n.mapping!==Jh?(Br.copy(s.backgroundRotation),Br.x*=-1,Br.y*=-1,Br.z*=-1,_c.makeRotationFromEuler(Br)):_c.identity(),_c}):console.error("THREE.SceneNode: Unknown scope:",t),i}}zt.BACKGROUND_BLURRINESS="backgroundBlurriness";zt.BACKGROUND_INTENSITY="backgroundIntensity";zt.BACKGROUND_ROTATION="backgroundRotation";const Zw=G(zt,zt.BACKGROUND_BLURRINESS),Pp=G(zt,zt.BACKGROUND_INTENSITY),Qw=G(zt,zt.BACKGROUND_ROTATION),Kw=L(({texture:o,uv:e})=>{const s=I().toVar();return Ze(e.x.lessThan(1e-4),()=>{s.assign(I(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{s.assign(I(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{s.assign(I(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{s.assign(I(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{s.assign(I(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{s.assign(I(0,0,-1))}).Else(()=>{const n=o.sample(e.add(I(-.01,0,0))).r.sub(o.sample(e.add(I(.01,0,0))).r),r=o.sample(e.add(I(0,-.01,0))).r.sub(o.sample(e.add(I(0,.01,0))).r),a=o.sample(e.add(I(0,0,-.01))).r.sub(o.sample(e.add(I(0,0,.01))).r);s.assign(I(n,r,a))}),s.normalize()});class Jw extends xr{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return I(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(ke(rr(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Kw({texture:this,uv:e})}}const eM=U(Jw).setParameterLength(1,3),ea=new ce;class tM extends xr{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Fp extends tM{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class Ml extends nt{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const n=new Is;n.isRenderTargetTexture=!0,n.name="depth";const r=new fn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:rs,...i});r.texture.name="output",r.depthTexture=n,this.renderTarget=r,this._textures={output:r.texture,depth:n},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=K(0),this._cameraFar=K(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=he.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];return t===void 0&&(t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)),t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(t!==void 0){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return t===void 0&&(t=k(new Fp(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=k(new Fp(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=$g(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar,n=this.getViewZNode(e);this._linearDepthNodes[e]=t=uo(n,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,e.backend.isWebGLBackend===!0&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Ml.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,n;const r=t.getOutputRenderTarget();r&&r.isXRRenderTarget===!0?(n=1,i=t.xr.getCamera(),t.xr.updateCamera(i),ea.set(r.width,r.height)):(i=this.camera,n=t.getPixelRatio(),t.getSize(ea)),this._pixelRatio=n,this.setSize(ea.width,ea.height);const a=t.getRenderTarget(),l=t.getMRT(),c=i.layers.mask;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(const h in this._previousTextures)this.toggleTexture(h);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(a),t.setMRT(l),i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Ml.COLOR="color";Ml.DEPTH="depth";const sM=L(([o,e])=>o.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),iM=L(([o,e])=>(o=o.mul(e),o.div(o.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),nM=L(([o,e])=>{o=o.mul(e),o=o.sub(.004).max(0);const t=o.mul(o.mul(6.2).add(.5)),s=o.mul(o.mul(6.2).add(1.7)).add(.06);return t.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),rM=L(([o])=>{const e=o.mul(o.add(.0245786)).sub(90537e-9),t=o.mul(o.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),oM=L(([o,e])=>{const t=Ft(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Ft(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return o=o.mul(e).div(.6),o=t.mul(o),o=rM(o),o=s.mul(o),o.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),aM=Ft(I(1.6605,-.1246,-.0182),I(-.5876,1.1329,-.1006),I(-.0728,-.0083,1.1187)),lM=Ft(I(.6274,.0691,.0164),I(.3293,.9195,.088),I(.0433,.0113,.8956)),cM=L(([o])=>{const e=I(o).toVar(),t=I(e.mul(e)).toVar(),s=I(t.mul(t)).toVar();return B(15.5).mul(s.mul(t)).sub(fe(40.14,s.mul(e))).add(fe(31.96,s).sub(fe(6.868,t.mul(e))).add(fe(.4298,t).add(fe(.1191,e).sub(.00232))))}),hM=L(([o,e])=>{const t=I(o).toVar(),s=Ft(I(.856627153315983,.137318972929847,.11189821299995),I(.0951212405381588,.761241990602591,.0767994186031903),I(.0482516061458583,.101439036467562,.811302368396859)),i=Ft(I(1.1271005818144368,-.1413297634984383,-.14132976349843826),I(-.11060664309660323,1.157823702216272,-.11060664309660294),I(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=B(-12.47393),r=B(4.026069);return t.mulAssign(e),t.assign(lM.mul(t)),t.assign(s.mul(t)),t.assign(vt(t,1e-10)),t.assign(ii(t)),t.assign(t.sub(n).div(r.sub(n))),t.assign(ai(t,0,1)),t.assign(cM(t)),t.assign(i.mul(t)),t.assign(gl(vt(I(0),t),I(2.2))),t.assign(aM.mul(t)),t.assign(ai(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),uM=L(([o,e])=>{const t=B(.76),s=B(.15);o=o.mul(e);const i=dr(o.r,dr(o.g,o.b)),n=Tt(i.lessThan(.08),i.sub(fe(6.25,i.mul(i))),.04);o.subAssign(n);const r=vt(o.r,vt(o.g,o.b));Ze(r.lessThan(t),()=>o);const a=At(1,t),l=At(1,a.mul(a).div(r.add(a.sub(t))));o.mulAssign(l.div(r));const c=At(1,Us(1,s.mul(r.sub(l)).add(1)));return Ve(o,I(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class ct extends re{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const i of t)i.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class dM extends ct{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return s===void 0&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,n=s.type,r=e.getCodeFromNode(this,n);i!==""&&(r.name=i);const a=e.getPropertyName(r),l=this.getNodeFunction(e).getCode(a);return r.code=l+`
|
|
74
|
-
`,t==="property"?a:e.format(`${a}()`,n,t)}}function
|
|
75
|
-
`):e.addLineFlowCode(`${t}Barrier()`,this)}}U(mM);class Vs extends re{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,n=this.getNodeType(e),r=this.getInputType(e),a=this.pointerNode,l=this.valueNode,c=[];c.push(`&${a.build(e,r)}`),l!==null&&c.push(l.build(e,r));const h=`${e.getMethod(i,n)}( ${c.join(", ")} )`;if(s.length===1&&s[0].isStackNode===!0)e.addLineFlowCode(h,this);else return t.constNode===void 0&&(t.constNode=pr(h,n).toConst()),t.constNode.build(e)}}Vs.ATOMIC_LOAD="atomicLoad";Vs.ATOMIC_STORE="atomicStore";Vs.ATOMIC_ADD="atomicAdd";Vs.ATOMIC_SUB="atomicSub";Vs.ATOMIC_MAX="atomicMax";Vs.ATOMIC_MIN="atomicMin";Vs.ATOMIC_AND="atomicAnd";Vs.ATOMIC_OR="atomicOr";Vs.ATOMIC_XOR="atomicXor";U(Vs);let ta;function Cl(o){ta=ta||new WeakMap;let e=ta.get(o);return e===void 0&&ta.set(o,e={}),e}function ny(o){const e=Cl(o);return e.shadowMatrix||(e.shadowMatrix=K("mat4").setGroup(Q).onRenderUpdate(t=>((o.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&o.shadow.updateMatrices(o),o.shadow.matrix)))}function gM(o,e=So){const t=ny(o).mul(e);return t.xyz.div(t.w)}function ry(o){const e=Cl(o);return e.position||(e.position=K(new N).setGroup(Q).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(o.matrixWorld)))}function yM(o){const e=Cl(o);return e.targetPosition||(e.targetPosition=K(new N).setGroup(Q).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(o.target.matrixWorld)))}function oy(o){const e=Cl(o);return e.viewPosition||(e.viewPosition=K(new N).setGroup(Q).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new N,s.value.setFromMatrixPosition(o.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const ay=o=>hi.transformDirection(ry(o).sub(yM(o))),xM=o=>o.sort((e,t)=>e.id-t.id),_M=(o,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===o)return t;return null},bc=new WeakMap,Ir=[];class ly extends re{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=I().toVar(),this.totalSpecularNode=I().toVar(),this.outgoingLightNode=I().toVar(),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let s=0;s<e.length;s++){const i=e[s];if(Ir.push(i.id),Ir.push(i.castShadow?1:0),i.isSpotLight===!0){const n=i.map!==null?i.map.id:-1,r=i.colorNode?i.colorNode.getCacheKey():-1;Ir.push(n,r)}}const t=lu(Ir);return Ir.length=0,t}getHash(e){if(this._lightNodesHash===null){this._lightNodes===null&&this.setupLightsNode(e);const t=[];for(const s of this._lightNodes)t.push(s.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=xM(this._lights),n=e.renderer.library;for(const r of i)if(r.isNode)t.push(k(r));else{let a=null;if(s!==null&&(a=_M(r.id,s)),a===null){const l=n.getLightNodeClass(r.constructor);if(l===null){console.warn(`LightsNode.setupNodeLights: Light node not found for ${r.constructor.name}`);continue}let c=null;bc.has(r)?c=bc.get(r):(c=k(new l(r)),bc.set(r,c)),t.push(c)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.direct({...s,lightNode:t,reflectedLight:n},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:n},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return this._lightNodes===null&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,n=i.lightingModel,r=e.getNodeProperties(this);if(n){const{totalDiffuseNode:a,totalSpecularNode:l}=this;i.outgoingLight=s;const c=e.addStack();r.nodes=c.nodes,n.start(e);const{backdrop:h,backdropAlpha:u}=i,{directDiffuse:d,directSpecular:p,indirectDiffuse:f,indirectSpecular:m}=i.reflectedLight;let y=d.add(f);h!==null&&(u!==null?y=I(u.mix(y,h)):y=I(h),i.material.transparent=!0),a.assign(y),l.assign(p.add(m)),s.assign(a.add(l)),n.finish(e),s=s.bypass(e.removeStack())}else r.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class bM extends re{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=he.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){cy.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||So)}}const cy=lg("vec3","shadowPositionWorld");function TM(o,e={}){return e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure,e.outputColorSpace=o.outputColorSpace,e.renderTarget=o.getRenderTarget(),e.activeCubeFace=o.getActiveCubeFace(),e.activeMipmapLevel=o.getActiveMipmapLevel(),e.renderObjectFunction=o.getRenderObjectFunction(),e.pixelRatio=o.getPixelRatio(),e.mrt=o.getMRT(),e.clearColor=o.getClearColor(e.clearColor||new ve),e.clearAlpha=o.getClearAlpha(),e.autoClear=o.autoClear,e.scissorTest=o.getScissorTest(),e}function SM(o,e){return e=TM(o,e),o.setMRT(null),o.setRenderObjectFunction(null),o.setClearColor(0,1),o.autoClear=!0,e}function vM(o,e){o.toneMapping=e.toneMapping,o.toneMappingExposure=e.toneMappingExposure,o.outputColorSpace=e.outputColorSpace,o.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),o.setRenderObjectFunction(e.renderObjectFunction),o.setPixelRatio(e.pixelRatio),o.setMRT(e.mrt),o.setClearColor(e.clearColor,e.clearAlpha),o.autoClear=e.autoClear,o.setScissorTest(e.scissorTest)}function wM(o,e={}){return e.background=o.background,e.backgroundNode=o.backgroundNode,e.overrideMaterial=o.overrideMaterial,e}function MM(o,e){return e=wM(o,e),o.background=null,o.backgroundNode=null,o.overrideMaterial=null,e}function CM(o,e){o.background=e.background,o.backgroundNode=e.backgroundNode,o.overrideMaterial=e.overrideMaterial}function EM(o,e,t){return t=SM(o,t),t=MM(e,t),t}function AM(o,e,t){vM(o,t),CM(e,t)}const Op=new WeakMap,RM=L(({depthTexture:o,shadowCoord:e,depthLayer:t})=>{let s=_e(o,e.xy).label("t_basic");return o.isArrayTexture&&(s=s.depth(t)),s.compare(e.z)}),NM=L(({depthTexture:o,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(y,g)=>{let _=_e(o,y);return o.isArrayTexture&&(_=_.depth(s)),_.compare(g)},n=Be("mapSize","vec2",t).setGroup(Q),r=Be("radius","float",t).setGroup(Q),a=H(1).div(n),l=a.x.negate().mul(r),c=a.y.negate().mul(r),h=a.x.mul(r),u=a.y.mul(r),d=l.div(2),p=c.div(2),f=h.div(2),m=u.div(2);return Dt(i(e.xy.add(H(l,c)),e.z),i(e.xy.add(H(0,c)),e.z),i(e.xy.add(H(h,c)),e.z),i(e.xy.add(H(d,p)),e.z),i(e.xy.add(H(0,p)),e.z),i(e.xy.add(H(f,p)),e.z),i(e.xy.add(H(l,0)),e.z),i(e.xy.add(H(d,0)),e.z),i(e.xy,e.z),i(e.xy.add(H(f,0)),e.z),i(e.xy.add(H(h,0)),e.z),i(e.xy.add(H(d,m)),e.z),i(e.xy.add(H(0,m)),e.z),i(e.xy.add(H(f,m)),e.z),i(e.xy.add(H(l,u)),e.z),i(e.xy.add(H(0,u)),e.z),i(e.xy.add(H(h,u)),e.z)).mul(1/17)}),PM=L(({depthTexture:o,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(u,d)=>{let p=_e(o,u);return o.isArrayTexture&&(p=p.depth(s)),p.compare(d)},n=Be("mapSize","vec2",t).setGroup(Q),r=H(1).div(n),a=r.x,l=r.y,c=e.xy,h=Ui(c.mul(n).add(.5));return c.subAssign(h.mul(r)),Dt(i(c,e.z),i(c.add(H(a,0)),e.z),i(c.add(H(0,l)),e.z),i(c.add(r),e.z),Ve(i(c.add(H(a.negate(),0)),e.z),i(c.add(H(a.mul(2),0)),e.z),h.x),Ve(i(c.add(H(a.negate(),l)),e.z),i(c.add(H(a.mul(2),l)),e.z),h.x),Ve(i(c.add(H(0,l.negate())),e.z),i(c.add(H(0,l.mul(2))),e.z),h.y),Ve(i(c.add(H(a,l.negate())),e.z),i(c.add(H(a,l.mul(2))),e.z),h.y),Ve(Ve(i(c.add(H(a.negate(),l.negate())),e.z),i(c.add(H(a.mul(2),l.negate())),e.z),h.x),Ve(i(c.add(H(a.negate(),l.mul(2))),e.z),i(c.add(H(a.mul(2),l.mul(2))),e.z),h.x),h.y)).mul(1/9)}),FM=L(({depthTexture:o,shadowCoord:e,depthLayer:t})=>{const s=B(1).toVar();let i=_e(o).sample(e.xy);o.isArrayTexture&&(i=i.depth(t)),i=i.rg;const n=Sg(e.z,i.x);return Ze(n.notEqual(B(1)),()=>{const r=e.z.sub(i.x),a=vt(0,i.y.mul(i.y));let l=a.div(a.add(r.mul(r)));l=ai(At(l,.3).div(.95-.3)),s.assign(ai(vt(n,l)))}),s}),DM=L(([o,e,t])=>{let s=So.sub(o).length();return s=s.sub(e).div(t.sub(e)),s=s.saturate(),s}),OM=o=>{const e=o.shadow.camera,t=Be("near","float",e).setGroup(Q),s=Be("far","float",e).setGroup(Q),i=qS(o);return DM(i,t,s)},BM=o=>{let e=Op.get(o);if(e===void 0){const t=o.isPointLight?OM(o):null;e=new it,e.colorNode=ne(0,0,0,1),e.depthNode=t,e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.fog=!1,Op.set(o,e)}return e},Bp=new vs,Dn=[],IM=(o,e,t,s)=>{Dn[0]=o,Dn[1]=e;let i=Bp.get(Dn);return(i===void 0||i.shadowType!==t||i.useVelocity!==s)&&(i=(n,r,a,l,c,h,...u)=>{(n.castShadow===!0||n.receiveShadow&&t===Aa)&&(s&&(qm(n).useVelocity=!0),n.onBeforeShadow(o,n,a,e.camera,l,r.overrideMaterial,h),o.renderObject(n,r,a,l,c,h,...u),n.onAfterShadow(o,n,a,e.camera,l,r.overrideMaterial,h))},i.shadowType=t,i.useVelocity=s,Bp.set(Dn,i)),Dn[0]=null,Dn[1]=null,i},LM=L(({samples:o,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanVertical"),r=B(0).toVar("squareMeanVertical"),a=o.lessThanEqual(B(1)).select(B(0),B(2).div(o.sub(1))),l=o.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:ke(0),end:ke(o),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(a));let d=s.sample(Dt(Sl.xy,H(0,u).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),r.addAssign(d.mul(d))}),n.divAssign(o),r.divAssign(o);const c=Su(r.sub(n.mul(n)));return H(n,c)}),UM=L(({samples:o,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanHorizontal"),r=B(0).toVar("squareMeanHorizontal"),a=o.lessThanEqual(B(1)).select(B(0),B(2).div(o.sub(1))),l=o.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:ke(0),end:ke(o),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(a));let d=s.sample(Dt(Sl.xy,H(u,0).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),r.addAssign(Dt(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(o),r.divAssign(o);const c=Su(r.sub(n.mul(n)));return H(n,c)}),kM=[RM,NM,PM,FM];let Tc;const sa=new Uu;class hy extends bM{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:n,depthLayer:r}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),l=t({depthTexture:s,shadowCoord:i,shadow:n,depthLayer:r});return a.select(l,B(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,n=Be("bias","float",s).setGroup(Q);let r=t,a;if(s.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)r=r.xyz.div(r.w),a=r.z,i.coordinateSystem===Oi&&(a=a.mul(2).sub(1));else{const l=r.w;r=r.xy.div(l);const c=Be("near","float",s.camera).setGroup(Q),h=Be("far","float",s.camera).setGroup(Q);a=jg(l.negate(),c,h)}return r=I(r.x,r.y.oneMinus(),a.add(n)),r}getShadowFilterFn(e){return kM[e]}setupRenderTarget(e,t){const s=new Is(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=au;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t}=e,{light:s,shadow:i}=this,n=t.shadowMap.type,{depthTexture:r,shadowMap:a}=this.setupRenderTarget(i,e);if(i.camera.updateProjectionMatrix(),n===Aa&&i.isPointLightShadow!==!0){r.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depthBuffer:!1}));let g=_e(r);r.isArrayTexture&&(g=g.depth(this.depthLayer));let _=_e(this.vsmShadowMapVertical.texture);r.isArrayTexture&&(_=_.depth(this.depthLayer));const b=Be("blurSamples","float",i).setGroup(Q),T=Be("radius","float",i).setGroup(Q),S=Be("mapSize","vec2",i).setGroup(Q);let C=this.vsmMaterialVertical||(this.vsmMaterialVertical=new it);C.fragmentNode=LM({samples:b,radius:T,size:S,shadowPass:g,depthLayer:this.depthLayer}).context(e.getSharedContext()),C.name="VSMVertical",C=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new it),C.fragmentNode=UM({samples:b,radius:T,size:S,shadowPass:_,depthLayer:this.depthLayer}).context(e.getSharedContext()),C.name="VSMHorizontal"}const l=Be("intensity","float",i).setGroup(Q),c=Be("normalBias","float",i).setGroup(Q),h=ny(s).mul(cy.add(Ou.mul(c))),u=this.setupShadowCoord(e,h),d=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(d===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=n===Aa&&i.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:r,f=this.setupShadowFilter(e,{filterFn:d,shadowTexture:a.texture,depthTexture:p,shadowCoord:u,shadow:i,depthLayer:this.depthLayer});let m=_e(a.texture,u);r.isArrayTexture&&(m=m.depth(this.depthLayer));const y=Ve(1,f.rgb.mix(m,1),l.mul(m.a)).toVar();return this.shadowMap=a,this.shadow.map=a,y}setup(e){if(e.renderer.shadowMap.enabled!==!1)return L(()=>{let t=this._node;return this.setupShadowPosition(e),t===null&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth),n.render(r,t.camera)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:n,scene:r,camera:a}=e,l=n.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;const h=i.camera.layers.mask;(i.camera.layers.mask&4294967294)===0&&(i.camera.layers.mask=a.layers.mask);const u=n.getRenderObjectFunction(),d=n.getMRT(),p=d?d.has("velocity"):!1;Tc=EM(n,r,Tc),r.overrideMaterial=BM(s),n.setRenderObjectFunction(IM(n,i,l,p)),n.setClearColor(0,0),n.setRenderTarget(t),this.renderShadow(e),n.setRenderObjectFunction(u),l===Aa&&i.isPointLightShadow!==!0&&this.vsmPass(n),i.camera.layers.mask=h,AM(n,r,Tc)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),sa.material=this.vsmMaterialVertical,sa.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),sa.material=this.vsmMaterialHorizontal,sa.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const zM=(o,e)=>k(new hy(o,e)),VM=new ve,Ps=L(([o,e])=>{const t=o.toVar(),s=ns(t),i=Us(1,vt(s.x,vt(s.y,s.z)));s.mulAssign(i),t.mulAssign(i.mul(e.mul(2).oneMinus()));const n=H(t.xy).toVar(),a=e.mul(1.5).oneMinus();return Ze(s.z.greaterThanEqual(a),()=>{Ze(t.z.greaterThan(0),()=>{n.x.assign(At(4,t.x))})}).ElseIf(s.x.greaterThanEqual(a),()=>{const l=ol(t.x);n.x.assign(t.z.mul(l).add(l.mul(2)))}).ElseIf(s.y.greaterThanEqual(a),()=>{const l=ol(t.y);n.x.assign(t.x.add(l.mul(2)).add(2)),n.y.assign(t.z.mul(l).sub(2))}),H(.125,.25).mul(n).add(H(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),GM=L(({depthTexture:o,bd3D:e,dp:t,texelSize:s})=>_e(o,Ps(e,s.y)).compare(t)),HM=L(({depthTexture:o,bd3D:e,dp:t,texelSize:s,shadow:i})=>{const n=Be("radius","float",i).setGroup(Q),r=H(-1,1).mul(n).mul(s.y);return _e(o,Ps(e.add(r.xyy),s.y)).compare(t).add(_e(o,Ps(e.add(r.yyy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.xyx),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yyx),s.y)).compare(t)).add(_e(o,Ps(e,s.y)).compare(t)).add(_e(o,Ps(e.add(r.xxy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yxy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.xxx),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yxx),s.y)).compare(t)).mul(1/9)}),WM=L(({filterFn:o,depthTexture:e,shadowCoord:t,shadow:s})=>{const i=t.xyz.toVar(),n=i.length(),r=K("float").setGroup(Q).onRenderUpdate(()=>s.camera.near),a=K("float").setGroup(Q).onRenderUpdate(()=>s.camera.far),l=Be("bias","float",s).setGroup(Q),c=K(s.mapSize).setGroup(Q),h=B(1).toVar();return Ze(n.sub(a).lessThanEqual(0).and(n.sub(r).greaterThanEqual(0)),()=>{const u=n.sub(r).div(a.sub(r)).toVar();u.addAssign(l);const d=i.normalize(),p=H(1).div(c.mul(H(4,2)));h.assign(o({depthTexture:e,bd3D:d,dp:u,texelSize:p,shadow:s}))}),h}),Ip=new ge,On=new ce,Lr=new ce;class $M extends hy{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===s_?GM:HM}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r}){return WM({filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r})}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e,a=t.getFrameExtents();Lr.copy(t.mapSize),Lr.multiply(a),s.setSize(Lr.width,Lr.height),On.copy(t.mapSize);const l=n.autoClear,c=n.getClearColor(VM),h=n.getClearAlpha();n.autoClear=!1,n.setClearColor(t.clearColor,t.clearAlpha),n.clear();const u=t.getViewportCount();for(let d=0;d<u;d++){const p=t.getViewport(d),f=On.x*p.x,m=Lr.y-On.y-On.y*p.y;Ip.set(f,m,On.x*p.z,On.y*p.w),s.viewport.copy(Ip),t.updateMatrices(i,d),n.render(r,t.camera)}n.autoClear=l,n.setClearColor(c,h)}}const jM=(o,e)=>k(new $M(o,e));class mn extends _r{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new ve,this.colorNode=e&&e.colorNode||K(this.color).setGroup(Q),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=he.FRAME}getHash(){return this.light.uuid}getLightVector(e){return oy(this.light).sub(e.context.positionView||st)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return zM(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let s=this.shadowColorNode;if(s===null){const i=this.light.shadow.shadowNode;let n;i!==void 0?n=k(i):n=this.setupShadowNode(),this.shadowNode=n,this.shadowColorNode=s=this.colorNode.mul(n),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const uy=L(({lightDistance:o,cutoffDistance:e,decayExponent:t})=>{const s=o.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(s.mul(o.div(e).pow4().oneMinus().clamp().pow2()),s)}),qM=({color:o,lightVector:e,cutoffDistance:t,decayExponent:s})=>{const i=e.normalize(),n=e.length(),r=uy({lightDistance:n,cutoffDistance:t,decayExponent:s}),a=o.mul(r);return{lightDirection:i,lightColor:a}};class YM extends mn{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=K(0).setGroup(Q),this.decayExponentNode=K(2).setGroup(Q)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return jM(this.light)}setupDirect(e){return qM({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const Lp=B(1),Gh=B(-2),ia=B(.8),Sc=B(-1),na=B(.4),vc=B(2),ra=B(.305),wc=B(3),Up=B(.21),XM=B(4),kp=B(4),ZM=B(16),QM=L(([o])=>{const e=I(ns(o)).toVar(),t=B(-1).toVar();return Ze(e.x.greaterThan(e.z),()=>{Ze(e.x.greaterThan(e.y),()=>{t.assign(Tt(o.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Tt(o.y.greaterThan(0),1,4))})}).Else(()=>{Ze(e.z.greaterThan(e.y),()=>{t.assign(Tt(o.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Tt(o.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),KM=L(([o,e])=>{const t=H().toVar();return Ze(e.equal(0),()=>{t.assign(H(o.z,o.y).div(ns(o.x)))}).ElseIf(e.equal(1),()=>{t.assign(H(o.x.negate(),o.z.negate()).div(ns(o.y)))}).ElseIf(e.equal(2),()=>{t.assign(H(o.x.negate(),o.y).div(ns(o.z)))}).ElseIf(e.equal(3),()=>{t.assign(H(o.z.negate(),o.y).div(ns(o.x)))}).ElseIf(e.equal(4),()=>{t.assign(H(o.x.negate(),o.z).div(ns(o.y)))}).Else(()=>{t.assign(H(o.x,o.y).div(ns(o.z)))}),fe(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),JM=L(([o])=>{const e=B(0).toVar();return Ze(o.greaterThanEqual(ia),()=>{e.assign(Lp.sub(o).mul(Sc.sub(Gh)).div(Lp.sub(ia)).add(Gh))}).ElseIf(o.greaterThanEqual(na),()=>{e.assign(ia.sub(o).mul(vc.sub(Sc)).div(ia.sub(na)).add(Sc))}).ElseIf(o.greaterThanEqual(ra),()=>{e.assign(na.sub(o).mul(wc.sub(vc)).div(na.sub(ra)).add(vc))}).ElseIf(o.greaterThanEqual(Up),()=>{e.assign(ra.sub(o).mul(XM.sub(wc)).div(ra.sub(Up)).add(wc))}).Else(()=>{e.assign(B(-2).mul(ii(fe(1.16,o))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),eC=L(([o,e])=>{const t=o.toVar();t.assign(fe(2,t).sub(1));const s=I(t,1).toVar();return Ze(e.equal(0),()=>{s.assign(s.zyx)}).ElseIf(e.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),tC=L(([o,e,t,s,i,n])=>{const r=B(t),a=I(e),l=ai(JM(r),Gh,n),c=Ui(l),h=un(l),u=I(Hh(o,a,h,s,i,n)).toVar();return Ze(c.notEqual(0),()=>{const d=I(Hh(o,a,h.add(1),s,i,n)).toVar();u.assign(Ve(u,d,c))}),u}),Hh=L(([o,e,t,s,i,n])=>{const r=B(t).toVar(),a=I(e),l=B(QM(a)).toVar(),c=B(vt(kp.sub(r),0)).toVar();r.assign(vt(r,kp));const h=B(bo(r)).toVar(),u=H(KM(a,l).mul(h.sub(2)).add(1)).toVar();return Ze(l.greaterThan(2),()=>{u.y.addAssign(h),l.subAssign(3)}),u.x.addAssign(l.mul(h)),u.x.addAssign(c.mul(fe(3,ZM))),u.y.addAssign(fe(4,bo(n).sub(h))),u.x.mulAssign(s),u.y.mulAssign(i),o.sample(u).grad(H(),H())}),Mc=L(({envMap:o,mipInt:e,outputDirection:t,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:r,CUBEUV_MAX_MIP:a})=>{const l=wi(s),c=t.mul(l).add(i.cross(t).mul(_s(s))).add(i.mul(i.dot(t).mul(l.oneMinus())));return Hh(o,c,e,n,r,a)}),sC=L(({n:o,latitudinal:e,poleAxis:t,outputDirection:s,weights:i,samples:n,dTheta:r,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})=>{const d=I(Tt(e,t,vg(t,s))).toVar();Ze(d.equal(I(0)),()=>{d.assign(I(s.z,0,s.x.negate()))}),d.assign(To(d));const p=I().toVar();return p.addAssign(i.element(0).mul(Mc({theta:0,axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),Ts({start:ke(1),end:o},({i:f})=>{Ze(f.greaterThanEqual(n),()=>{$S()});const m=B(r.mul(B(f))).toVar();p.addAssign(i.element(f).mul(Mc({theta:m.mul(-1),axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),p.addAssign(i.element(f).mul(Mc({theta:m,axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})))}),ne(p,1)}),yi=new N,zp=new ce,Vp=new ce;class Zt extends hu{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ar*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ro*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ar*2*Math.atan(Math.tan(ro*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){yi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(yi.x,yi.y).multiplyScalar(-e/yi.z),yi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(yi.x,yi.y).multiplyScalar(-e/yi.z)}getViewSize(e,t){return this.getViewBounds(e,zp,Vp),t.subVectors(Vp,zp)}setViewOffset(e,t,s,i,n,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ro*.5*this.fov)/this.zoom,s=2*t,i=this.aspect*s,n=-.5*i;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;n+=r.offsetX*i/l,t-=r.offsetY*s/c,i*=r.width/l,s*=r.height/c}const a=this.filmOffset;a!==0&&(n+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class Ro extends ui{constructor(e=1,t=1,s=1,i=1,n=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:n,depthSegments:r};const a=this;i=Math.floor(i),n=Math.floor(n),r=Math.floor(r);const l=[],c=[],h=[],u=[];let d=0,p=0;f("z","y","x",-1,-1,s,t,e,r,n,0),f("z","y","x",1,-1,s,t,-e,r,n,1),f("x","z","y",1,1,e,s,t,i,r,2),f("x","z","y",1,-1,e,s,-t,i,r,3),f("x","y","z",1,-1,e,t,s,i,n,4),f("x","y","z",-1,-1,e,t,-s,i,n,5),this.setIndex(l),this.setAttribute("position",new Pt(c,3)),this.setAttribute("normal",new Pt(h,3)),this.setAttribute("uv",new Pt(u,2));function f(m,y,g,_,b,T,S,C,w,R,P){const z=T/w,$=S/R,q=T/2,j=S/2,X=C/2,Z=w+1,we=R+1;let ue=0,ye=0;const se=new N;for(let Me=0;Me<we;Me++){const ze=Me*$-j;for(let ot=0;ot<Z;ot++){const be=ot*z-q;se[m]=be*_,se[y]=ze*b,se[g]=X,c.push(se.x,se.y,se.z),se[m]=0,se[y]=0,se[g]=C>0?1:-1,h.push(se.x,se.y,se.z),u.push(ot/w),u.push(1-Me/R),ue+=1}}for(let Me=0;Me<R;Me++)for(let ze=0;ze<w;ze++){const ot=d+ze+Z*Me,be=d+ze+Z*(Me+1),at=d+(ze+1)+Z*(Me+1),Ot=d+(ze+1)+Z*Me;l.push(ot,be,Ot),l.push(be,at,Ot),ye+=6}a.addGroup(p,ye,P),p+=ye,d+=ue}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ro(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}const Xn=4,Gp=[.125,.215,.35,.446,.526,.582],an=20,Cc=new Lu(-1,1,1,-1,0,1),iC=new Zt(90,1),Hp=new ve;let Ec=null,Ac=0,Rc=0;const sn=(1+Math.sqrt(5))/2,Bn=1/sn,Wp=[new N(-sn,Bn,0),new N(sn,Bn,0),new N(-Bn,0,sn),new N(Bn,0,sn),new N(0,sn,-Bn),new N(0,sn,Bn),new N(-1,1,-1),new N(1,1,-1),new N(-1,1,1),new N(1,1,1)],nC=new N,dy=new WeakMap,rC=[3,1,5,0,4,2],Nc=eC(Ao(),Ii("faceIndex")).normalize(),ku=I(Nc.x,Nc.y,Nc.z);class oC{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,n={}){const{size:r=256,position:a=nC,renderTarget:l=null}=n;if(this._setSize(r),this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const h=l||this._allocateTarget();return n.renderTarget=h,this.fromSceneAsync(e,t,s,i,n),h}Ec=this._renderer.getRenderTarget(),Ac=this._renderer.getActiveCubeFace(),Rc=this._renderer.getActiveMipmapLevel();const c=l||this._allocateTarget();return c.depthBuffer=!0,this._init(c),this._sceneToCubeUV(e,s,i,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,s=.1,i=100,n={}){return this._hasInitialized===!1&&await this._renderer.init(),this.fromScene(e,t,s,i,n)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=jp(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=qp(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===yo||e.mapping===Xa?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Ec,Ac,Rc),e.scissorTest=!1,oa(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Ec=this._renderer.getRenderTarget(),Ac=this._renderer.getActiveCubeFace(),Rc=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize;return $p(e,t)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=$p(e.width,e.height);const{_lodMax:t}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=aC(t)),this._blurMaterial=lC(t,e.width,e.height)}}async _compileMaterial(e){const t=new li(this._lodPlanes[0],e);await this._renderer.compile(t,Cc)}_sceneToCubeUV(e,t,s,i,n){const r=iC;r.near=t,r.far=s;const a=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,h=c.autoClear;c.getClearColor(Hp),c.autoClear=!1;let u=this._backgroundBox;if(u===null){const f=new Ai({name:"PMREM.Background",side:Vt,depthWrite:!1,depthTest:!1});u=new li(new Ro,f)}let d=!1;const p=e.background;p?p.isColor&&(u.material.color.copy(p),e.background=null,d=!0):(u.material.color.copy(Hp),d=!0),c.setRenderTarget(i),c.clear(),d&&c.render(u,r);for(let f=0;f<6;f++){const m=f%3;m===0?(r.up.set(0,a[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x+l[f],n.y,n.z)):m===1?(r.up.set(0,0,a[f]),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y+l[f],n.z)):(r.up.set(0,a[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y,n.z+l[f]));const y=this._cubeSize;oa(i,m*y,f>2?y:0,y,y),c.render(e,r)}c.autoClear=h,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===yo||e.mapping===Xa;i?this._cubemapMaterial===null&&(this._cubemapMaterial=jp(e)):this._equirectMaterial===null&&(this._equirectMaterial=qp(e));const n=i?this._cubemapMaterial:this._equirectMaterial;n.fragmentNode.value=e;const r=this._lodMeshes[0];r.material=n;const a=this._cubeSize;oa(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(r,Cc)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let n=1;n<i;n++){const r=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=Wp[(i-n-1)%Wp.length];this._blur(e,n-1,n,r,a)}t.autoClear=s}_blur(e,t,s,i,n){const r=this._pingPongRenderTarget;this._halfBlur(e,r,t,s,i,"latitudinal",n),this._halfBlur(r,e,s,s,i,"longitudinal",n)}_halfBlur(e,t,s,i,n,r,a){const l=this._renderer,c=this._blurMaterial;r!=="latitudinal"&&r!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[i];u.material=c;const d=dy.get(c),p=this._sizeLods[s]-1,f=isFinite(n)?Math.PI/(2*p):2*Math.PI/(2*an-1),m=n/f,y=isFinite(n)?1+Math.floor(h*m):an;y>an&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${an}`);const g=[];let _=0;for(let w=0;w<an;++w){const R=w/m,P=Math.exp(-R*R/2);g.push(P),w===0?_+=P:w<y&&(_+=2*P)}for(let w=0;w<g.length;w++)g[w]=g[w]/_;e.texture.frame=(e.texture.frame||0)+1,d.envMap.value=e.texture,d.samples.value=y,d.weights.array=g,d.latitudinal.value=r==="latitudinal"?1:0,a&&(d.poleAxis.value=a);const{_lodMax:b}=this;d.dTheta.value=f,d.mipInt.value=b-s;const T=this._sizeLods[i],S=3*T*(i>b-Xn?i-b+Xn:0),C=4*(this._cubeSize-T);oa(t,S,C,3*T,2*T),l.setRenderTarget(t),l.render(u,Cc)}}function aC(o){const e=[],t=[],s=[],i=[];let n=o;const r=o-Xn+1+Gp.length;for(let a=0;a<r;a++){const l=Math.pow(2,n);t.push(l);let c=1/l;a>o-Xn?c=Gp[a-o+Xn-1]:a===0&&(c=0),s.push(c);const h=1/(l-2),u=-h,d=1+h,p=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,m=6,y=3,g=2,_=1,b=new Float32Array(y*m*f),T=new Float32Array(g*m*f),S=new Float32Array(_*m*f);for(let w=0;w<f;w++){const R=w%3*2/3-1,P=w>2?0:-1,z=[R,P,0,R+2/3,P,0,R+2/3,P+1,0,R,P,0,R+2/3,P+1,0,R,P+1,0],$=rC[w];b.set(z,y*m*$),T.set(p,g*m*$);const q=[$,$,$,$,$,$];S.set(q,_*m*$)}const C=new ui;C.setAttribute("position",new ls(b,y)),C.setAttribute("uv",new ls(T,g)),C.setAttribute("faceIndex",new ls(S,_)),e.push(C),i.push(new li(C,null)),n>Xn&&n--}return{lodPlanes:e,sizeLods:t,sigmas:s,lodMeshes:i}}function $p(o,e){const t={magFilter:Kt,minFilter:Kt,generateMipmaps:!1,type:rs,format:os,colorSpace:Jn},s=new fn(o,e,t);return s.texture.mapping=fh,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function oa(o,e,t,s,i){o.viewport.set(e,t,s,i),o.scissor.set(e,t,s,i)}function zu(o){const e=new it;return e.depthTest=!1,e.depthWrite=!1,e.blending=lr,e.name=`PMREM_${o}`,e}function lC(o,e,t){const s=Os(new Array(an).fill(0)),i=K(new N(0,1,0)),n=K(0),r=B(an),a=K(0),l=K(1),c=_e(null),h=K(0),u=B(1/e),d=B(1/t),p=B(o),f={n:r,latitudinal:a,weights:s,poleAxis:i,outputDirection:ku,dTheta:n,samples:l,envMap:c,mipInt:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=zu("blur");return m.fragmentNode=sC({...f,latitudinal:a.equal(1)}),dy.set(m,f),m}function jp(o){const e=zu("cubemap");return e.fragmentNode=vo(o,ku),e}function qp(o){const e=zu("equirect");return e.fragmentNode=_e(o,Ug(ku),0),e}const Yp=new WeakMap;function cC(o){const e=Math.log2(o)-2,t=1/o;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:t,maxMip:e}}function hC(o,e,t){const s=uC(e);let i=s.get(o);if((i!==void 0?i.pmremVersion:-1)!==o.pmremVersion){const r=o.image;if(o.isCubeTexture)if(pC(r))i=t.fromCubemap(o,i);else return null;else if(fC(r))i=t.fromEquirectangular(o,i);else return null;i.pmremVersion=o.pmremVersion,s.set(o,i)}return i.texture}function uC(o){let e=Yp.get(o);return e===void 0&&(e=new WeakMap,Yp.set(o,e)),e}class dC extends nt{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new St;i.isRenderTargetTexture=!0,this._texture=_e(i),this._width=K(0),this._height=K(0),this._maxMip=K(0),this.updateBeforeType=he.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=cC(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(i.isPMREMTexture===!0?t=i:t=hC(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new oC(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this)),t=Xg.mul(I(t.x,t.y.negate(),t.z));let s=this.levelNode;return s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),tC(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function pC(o){if(o==null)return!1;let e=0;const t=6;for(let s=0;s<t;s++)o[s]!==void 0&&e++;return e===t}function fC(o){return o==null?!1:o.height>0}const py=U(dC).setParameterLength(1,3);L(([o=Ao()],{renderer:e,material:t})=>{const s=Mg(o.mul(2).sub(1));let i;if(t.alphaToCoverage&&e.samples>1){const n=B(s.fwidth()).toVar();i=Bi(n.oneMinus(),n.add(1),s).oneMinus()}else i=Tt(s.greaterThan(1),0,1);return i});const wo=L(({f0:o,f90:e,dotVH:t})=>{const s=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return o.mul(s.oneMinus()).add(e.mul(s))}),mC=L(({alpha:o,dotNL:e,dotNV:t})=>{const s=o.pow2(),i=e.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt()),n=t.mul(s.add(s.oneMinus().mul(e.pow2())).sqrt());return Us(.5,i.add(n).max(PT))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),gC=L(({alphaT:o,alphaB:e,dotTV:t,dotBV:s,dotTL:i,dotBL:n,dotNV:r,dotNL:a})=>{const l=a.mul(I(o.mul(t),e.mul(s),r).length()),c=r.mul(I(o.mul(i),e.mul(n),a).length());return Us(.5,l.add(c)).saturate()}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),yC=L(({alpha:o,dotNH:e})=>{const t=o.pow2(),s=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),xC=B(1/Math.PI),_C=L(({alphaT:o,alphaB:e,dotNH:t,dotTH:s,dotBH:i})=>{const n=o.mul(e),r=I(e.mul(s),o.mul(i),n.mul(t)),a=r.dot(r),l=n.div(a);return xC.mul(n.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),Xp=L(o=>{const{lightDirection:e,f0:t,f90:s,roughness:i,f:n,USE_IRIDESCENCE:r,USE_ANISOTROPY:a}=o,l=o.normalView||et,c=i.pow2(),h=e.add(je).normalize(),u=l.dot(e).clamp(),d=l.dot(je).clamp(),p=l.dot(h).clamp(),f=je.dot(h).clamp();let m=wo({f0:t,f90:s,dotVH:f}),y,g;if(ip(r)&&(m=Tu.mix(m,n)),ip(a)){const _=Fa.dot(e),b=Fa.dot(je),T=Fa.dot(h),S=ir.dot(e),C=ir.dot(je),w=ir.dot(h);y=gC({alphaT:Ih,alphaB:c,dotTV:b,dotBV:C,dotTL:_,dotBL:S,dotNV:d,dotNL:u}),g=_C({alphaT:Ih,alphaB:c,dotNH:p,dotTH:T,dotBH:w})}else y=mC({alpha:c,dotNL:u,dotNV:d}),g=yC({alpha:c,dotNH:p});return m.mul(y).mul(g)}),fr=L(o=>o.diffuseColor.mul(1/Math.PI)),fy=L(({roughness:o,dotNV:e})=>{const t=ne(-1,-.0275,-.572,.022),s=ne(1,.0425,1.04,-.04),i=o.mul(t).add(s),n=i.x.mul(i.x).min(e.mul(-9.28).exp2()).mul(i.x).add(i.y);return H(-1.04,1.04).mul(n).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),bC=L(({f:o,f90:e,dotVH:t})=>{const s=t.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return o.sub(I(e).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),TC=L(o=>{if(o.geometry.hasAttribute("normal")===!1)return B(0);const e=zs.dFdx().abs().max(zs.dFdy().abs());return e.x.max(e.y).max(e.z)}),my=L(o=>{const{roughness:e}=o,t=TC();let s=e.max(.0525);return s=s.add(t),s=s.min(1),s}),SC=L(([o,e])=>{const t=o.x,s=o.y,i=o.z;let n=e.element(0).mul(.886227);return n=n.add(e.element(1).mul(2*.511664).mul(s)),n=n.add(e.element(2).mul(2*.511664).mul(i)),n=n.add(e.element(3).mul(2*.511664).mul(t)),n=n.add(e.element(4).mul(2*.429043).mul(t).mul(s)),n=n.add(e.element(5).mul(2*.429043).mul(s).mul(i)),n=n.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(e.element(7).mul(2*.429043).mul(t).mul(i)),n=n.add(e.element(8).mul(.429043).mul(fe(t,t).sub(fe(s,s)))),n});class Vu extends ui{constructor(e=1,t=32,s=16,i=0,n=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:n,thetaStart:r,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const l=Math.min(r+a,Math.PI);let c=0;const h=[],u=new N,d=new N,p=[],f=[],m=[],y=[];for(let g=0;g<=s;g++){const _=[],b=g/s;let T=0;g===0&&r===0?T=.5/t:g===s&&l===Math.PI&&(T=-.5/t);for(let S=0;S<=t;S++){const C=S/t;u.x=-e*Math.cos(i+C*n)*Math.sin(r+b*a),u.y=e*Math.cos(r+b*a),u.z=e*Math.sin(i+C*n)*Math.sin(r+b*a),f.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),y.push(C+T,1-b),_.push(c++)}h.push(_)}for(let g=0;g<s;g++)for(let _=0;_<t;_++){const b=h[g][_+1],T=h[g][_],S=h[g+1][_],C=h[g+1][_+1];(g!==0||r>0)&&p.push(b,T,C),(g!==s-1||l<Math.PI)&&p.push(T,S,C)}this.setIndex(p),this.setAttribute("position",new Pt(f,3)),this.setAttribute("normal",new Pt(m,3)),this.setAttribute("uv",new Pt(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vu(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}const gs=new du;class vC extends Li{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,n=this.nodes.getBackgroundNode(e)||e.background;let r=!1;if(n===null)i._clearColor.getRGB(gs),gs.a=i._clearColor.a;else if(n.isColor===!0)n.getRGB(gs),gs.a=1,r=!0;else if(n.isNode===!0){const l=this.get(e),c=n;gs.copy(i._clearColor);let h=l.backgroundMesh;if(h===void 0){let m=function(){n.removeEventListener("dispose",m),h.material.dispose(),h.geometry.dispose()};const d=Mu(ne(c).mul(Pp),{getUV:()=>Qw.mul(Du),getTextureLevel:()=>Zw});let p=ey;p=p.setZ(p.w);const f=new it;f.name="Background.material",f.side=Vt,f.depthTest=!1,f.depthWrite=!1,f.allowOverride=!1,f.fog=!1,f.lights=!1,f.vertexNode=p,f.colorNode=d,l.backgroundMeshNode=d,l.backgroundMesh=h=new li(new Vu(1,32,32),f),h.frustumCulled=!1,h.name="Background.mesh",h.onBeforeRender=function(y,g,_){this.matrixWorld.copyPosition(_.matrixWorld)},n.addEventListener("dispose",m)}const u=c.getCacheKey();l.backgroundCacheKey!==u&&(l.backgroundMeshNode.node=ne(c).mul(Pp),l.backgroundMeshNode.needsUpdate=!0,h.material.needsUpdate=!0,l.backgroundCacheKey=u),t.unshift(h,h.geometry,h.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",n);const a=i.xr.getEnvironmentBlendMode();if(a==="additive"?gs.set(0,0,0,1):a==="alpha-blend"&&gs.set(0,0,0,0),i.autoClear===!0||r===!0){const l=s.clearColorValue;l.r=gs.r,l.g=gs.g,l.b=gs.b,l.a=gs.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=i.autoClearColor===!0,s.clearDepth=i.autoClearDepth===!0,s.clearStencil=i.autoClearStencil===!0}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let wC=0;class Wh{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=wC++}}class MC{constructor(e,t,s,i,n,r,a,l,c,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=h,this.nodeAttributes=i,this.bindings=n,this.updateNodes=r,this.updateBeforeNodes=a,this.updateAfterNodes=l,this.observer=c,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const i=new Wh(t.name,[],t.index,t);e.push(i);for(const n of t.bindings)i.bindings.push(n.clone())}else e.push(t);return e}}function gy(o){const e={};for(const t in o){e[t]={};for(const s in o[t]){const i=o[t][s];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][s]=null):e[t][s]=i.clone():Array.isArray(i)?e[t][s]=i.slice():e[t][s]=i}}return e}function CC(o){const e=[];for(let t=0;t<o.length;t++)e.push(o[t].clone());return e}const EC=`
|
|
73
|
+
`).removeFlowTab();return e.addFlowTab(),r}}const Ts=(...o)=>k(new fv(ir(o,"int"))).toStack(),mv=()=>mr("break").toStack();class Ao{constructor(e=new N(1/0,1/0,1/0),t=new N(-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,s=e.length;t<s;t+=3)this.expandByPoint(fs.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(fs.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=fs.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),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);const s=e.geometry;if(s!==void 0){const n=s.getAttribute("position");if(t===!0&&n!==void 0&&e.isInstancedMesh!==!0)for(let r=0,a=n.count;r<a;r++)e.isMesh===!0?e.getVertexPosition(r,fs):fs.fromBufferAttribute(n,r),fs.applyMatrix4(e.matrixWorld),this.expandByPoint(fs);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ho.copy(e.boundingBox)):(s.boundingBox===null&&s.computeBoundingBox(),Ho.copy(s.boundingBox)),Ho.applyMatrix4(e.matrixWorld),this.union(Ho)}const i=e.children;for(let n=0,r=i.length;n<r;n++)this.expandByObject(i[n],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,fs),fs.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Nr),Wo.subVectors(this.max,Nr),An.subVectors(e.a,Nr),Rn.subVectors(e.b,Nr),Nn.subVectors(e.c,Nr),fi.subVectors(Rn,An),mi.subVectors(Nn,Rn),Vi.subVectors(An,Nn);let t=[0,-fi.z,fi.y,0,-mi.z,mi.y,0,-Vi.z,Vi.y,fi.z,0,-fi.x,mi.z,0,-mi.x,Vi.z,0,-Vi.x,-fi.y,fi.x,0,-mi.y,mi.x,0,-Vi.y,Vi.x,0];return!tc(t,An,Rn,Nn,Wo)||(t=[1,0,0,0,1,0,0,0,1],!tc(t,An,Rn,Nn,Wo))?!1:($o.crossVectors(fi,mi),t=[$o.x,$o.y,$o.z],tc(t,An,Rn,Nn,Wo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fs).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(fs).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:(Hs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Hs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Hs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Hs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Hs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Hs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Hs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Hs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Hs),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}}const Hs=[new N,new N,new N,new N,new N,new N,new N,new N],fs=new N,Ho=new Ao,An=new N,Rn=new N,Nn=new N,fi=new N,mi=new N,Vi=new N,Nr=new N,Wo=new N,$o=new N,Hi=new N;function tc(o,e,t,s,i){for(let n=0,r=o.length-3;n<=r;n+=3){Hi.fromArray(o,n);const a=i.x*Math.abs(Hi.x)+i.y*Math.abs(Hi.y)+i.z*Math.abs(Hi.z),l=e.dot(Hi),c=t.dot(Hi),h=s.dot(Hi);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}const gv=new Ao,Pr=new N,sc=new N;class bl{constructor(e=new N,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){const s=this.center;t!==void 0?s.copy(t):gv.setFromPoints(e).getCenter(s);let i=0;for(let n=0,r=e.length;n<r;n++)i=Math.max(i,s.distanceToSquared(e[n]));return this.radius=Math.sqrt(i),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){const 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){const s=this.center.distanceToSquared(e);return t.copy(e),s>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=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;Pr.subVectors(e,this.center);const t=Pr.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),i=(s-this.radius)*.5;this.center.addScaledVector(Pr,i/s),this.radius+=i}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):(sc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Pr.copy(e.center).add(sc)),this.expandByPoint(Pr.copy(e.center).sub(sc))),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}}const dp=new bl;class Pe extends re{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ue.OBJECT,this.uniformNode=new Eo(null)}getNodeType(){const e=this.scope;if(e===Pe.WORLD_MATRIX)return"mat4";if(e===Pe.POSITION||e===Pe.VIEW_POSITION||e===Pe.DIRECTION||e===Pe.SCALE)return"vec3";if(e===Pe.RADIUS)return"float"}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Pe.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Pe.POSITION)s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Pe.SCALE)s.value=s.value||new N,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Pe.DIRECTION)s.value=s.value||new N,t.getWorldDirection(s.value);else if(i===Pe.VIEW_POSITION){const n=e.camera;s.value=s.value||new N,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(n.matrixWorldInverse)}else if(i===Pe.RADIUS){const n=e.object.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),dp.copy(n.boundingSphere).applyMatrix4(t.matrixWorld),s.value=dp.radius}}generate(e){const t=this.scope;return t===Pe.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Pe.POSITION||t===Pe.VIEW_POSITION||t===Pe.DIRECTION||t===Pe.SCALE?this.uniformNode.nodeType="vec3":t===Pe.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Pe.WORLD_MATRIX="worldMatrix";Pe.POSITION="position";Pe.SCALE="scale";Pe.VIEW_POSITION="viewPosition";Pe.DIRECTION="direction";Pe.RADIUS="radius";const yv=U(Pe,Pe.POSITION).setParameterLength(1);class Ug extends Eo{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const kg=(o,e,t)=>k(new Ug(o,e,t));class xv extends Co{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class _v extends Ug{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?sl(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ue.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if(s==="float"||s==="int"||s==="uint")for(let i=0;i<e.length;i++){const n=i*4;t[n]=e[i]}else if(s==="color")for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.r,t[n+1]=r.g,t[n+2]=r.b||0}else if(s==="mat2")for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+3]=r.elements[3]}else if(s==="mat3")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];t[n]=r.elements[0],t[n+1]=r.elements[1],t[n+2]=r.elements[2],t[n+4]=r.elements[3],t[n+5]=r.elements[4],t[n+6]=r.elements[5],t[n+8]=r.elements[6],t[n+9]=r.elements[7],t[n+10]=r.elements[8],t[n+15]=1}else if(s==="mat4")for(let i=0;i<e.length;i++){const n=i*16,r=e[i];for(let a=0;a<r.elements.length;a++)t[n+a]=r.elements[a]}else for(let i=0;i<e.length;i++){const n=i*4,r=e[i];t[n]=r.x,t[n+1]=r.y,t[n+2]=r.z||0,t[n+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const n=this.paddedType,r=e.getTypeLength(n);return s.charAt(0)==="i"&&(i=Int32Array),s.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*r),this.bufferCount=t,this.bufferType=n,super.setup(e)}element(e){return k(new xv(this,k(e)))}}const Os=(o,e)=>k(new _v(o,e));class bv extends re{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const Tl=U(bv).setParameterLength(1),zg=Q(0,"uint").label("u_cameraIndex").setGroup(Tu("cameraIndex")).toVarying("v_cameraIndex"),rn=Q("float").label("cameraNear").setGroup(K).onRenderUpdate(({camera:o})=>o.near),on=Q("float").label("cameraFar").setGroup(K).onRenderUpdate(({camera:o})=>o.far),Ou=L(({camera:o})=>{let e;if(o.isArrayCamera&&o.cameras.length>0){const t=[];for(const i of o.cameras)t.push(i.projectionMatrix);e=Os(t).setGroup(K).label("cameraProjectionMatrices").element(o.isMultiViewCamera?Tl("gl_ViewID_OVR"):zg).toVar("cameraProjectionMatrix")}else e=Q("mat4").label("cameraProjectionMatrix").setGroup(K).onRenderUpdate(({camera:t})=>t.projectionMatrix);return e}).once()(),hi=L(({camera:o})=>{let e;if(o.isArrayCamera&&o.cameras.length>0){const t=[];for(const i of o.cameras)t.push(i.matrixWorldInverse);e=Os(t).setGroup(K).label("cameraViewMatrices").element(o.isMultiViewCamera?Tl("gl_ViewID_OVR"):zg).toVar("cameraViewMatrix")}else e=Q("mat4").label("cameraViewMatrix").setGroup(K).onRenderUpdate(({camera:t})=>t.matrixWorldInverse);return e}).once()(),Tv=Q(new N).label("cameraPosition").setGroup(K).onRenderUpdate(({camera:o},e)=>e.value.setFromMatrixPosition(o.matrixWorld));class ds extends Pe{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}ds.DIRECTION;const dn=V(ds,ds.WORLD_MATRIX);ds.POSITION;ds.SCALE;ds.VIEW_POSITION;ds.RADIUS;const Sv=Q(new Ht).onObjectUpdate(({object:o},e)=>e.value.getNormalMatrix(o.matrixWorld)),Sl=L(o=>o.renderer.overrideNodes.modelViewMatrix||vv).once()().toVar("modelViewMatrix"),vv=hi.mul(dn),pp=L(o=>(o.context.isHighPrecisionModelViewMatrix=!0,Q("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),fp=L(o=>{const e=o.context.isHighPrecisionModelViewMatrix;return Q("mat3").onObjectUpdate(({object:t,camera:s})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),vl=Ii("position","vec3"),bt=vl.toVarying("positionLocal"),mp=vl.toVarying("positionPrevious"),vo=L(o=>dn.mul(bt).xyz.toVarying(o.getNamespace("v_positionWorld")),"vec3").once("POSITION")(),Gg=L(o=>bt.transformDirection(dn).toVarying(o.getNamespace("v_positionWorldDirection")).normalize().toVar("positionWorldDirection"),"vec3").once("POSITION")(),st=L(o=>o.context.setupPositionView().toVarying(o.getNamespace("v_positionView")),"vec3").once("POSITION")(),je=st.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class wv extends nt{static get type(){return"EquirectUVNode"}constructor(e=Gg){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan(e.x).mul(1/(Math.PI*2)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return H(t,s)}}const Vg=U(wv).setParameterLength(0,1);class Mv extends re{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Ut&&s.side===Gt?"false":e.getFrontFacing()}}const Cv=V(Mv),wl=B(Cv).mul(2).sub(1),Hg=Ii("normal","vec3"),ks=L(o=>o.geometry.hasAttribute("normal")===!1?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),I(0,1,0)):Hg,"vec3").once()().toVar("normalLocal"),Ev=st.dFdx().cross(st.dFdy()).normalize().toVar("normalFlat"),zs=L(o=>{let e;return o.material.flatShading===!0?e=Ev:e=ws(Wg(ks),"v_normalView").normalize(),e},"vec3").once()().toVar("normalView"),Bu=L(o=>{let e=zs.transformDirection(hi);return o.material.flatShading!==!0&&(e=ws(e,"v_normalWorld")),e},"vec3").once()().normalize().toVar("normalWorld"),et=L(o=>{let e=o.context.setupNormal().context({getUV:null});return o.material.flatShading!==!0&&(e=e.mul(wl)),e},"vec3").once()().toVar("transformedNormalView"),Iu=et.transformDirection(hi).toVar("transformedNormalWorld"),to=L(o=>{let e=o.context.setupClearcoatNormal().context({getUV:null});return o.material.flatShading!==!0&&(e=e.mul(wl)),e},"vec3").once()().toVar("transformedClearcoatNormalView"),Av=L(([o,e=dn])=>{const t=Ft(e),s=o.div(I(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(s).xyz}),Wg=L(([o],e)=>{const t=e.renderer.overrideNodes.modelNormalViewMatrix;if(t!==null)return t.transformDirection(o);const s=Sv.mul(o);return hi.transformDirection(s)});class Rv extends nt{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=I(je.z,0,je.x.negate()).normalize(),t=je.cross(e);return H(e.dot(et),t.dot(et)).mul(.495).add(.5)}}const Nv=V(Rv);class Pv extends Eo{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ue.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&s.width!==void 0){const{width:i,height:n}=s;this.value=Math.log2(Math.max(i,n))}}}const Fv=U(Pv).setParameterLength(1),Dv=o=>k(o).mul(.5).add(.5);class Ov extends nt{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if(this.getNodeType(e)==="vec2"){const n=t.cos(),r=t.sin();return bu(n,r,r.negate(),n).mul(s)}else{const n=t,r=nr(ne(1,0,0,0),ne(0,wi(n.x),_s(n.x).negate(),0),ne(0,_s(n.x),wi(n.x),0),ne(0,0,0,1)),a=nr(ne(wi(n.y),0,_s(n.y),0),ne(0,1,0,0),ne(_s(n.y).negate(),0,wi(n.y),0),ne(0,0,0,1)),l=nr(ne(wi(n.z),_s(n.z).negate(),0,0),ne(_s(n.z),wi(n.z),0,0),ne(0,0,1,0),ne(0,0,0,1));return r.mul(a).mul(l).mul(ne(s,1)).xyz}}}const $g=U(Ov).setParameterLength(2);let Fr,Dr;class Je extends re{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Je.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ue.NONE;return(this.scope===Je.SIZE||this.scope===Je.VIEWPORT)&&(e=ue.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Je.VIEWPORT?t!==null?Dr.copy(t.viewport):(e.getViewport(Dr),Dr.multiplyScalar(e.getPixelRatio())):t!==null?(Fr.width=t.width,Fr.height=t.height):e.getDrawingBufferSize(Fr)}setup(){const e=this.scope;let t=null;return e===Je.SIZE?t=Q(Fr||(Fr=new he)):e===Je.VIEWPORT?t=Q(Dr||(Dr=new ge)):t=H(Ml.div(Gh)),t}generate(e){if(this.scope===Je.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Gh).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Je.COORDINATE="coordinate";Je.VIEWPORT="viewport";Je.SIZE="size";Je.UV="uv";const or=V(Je,Je.UV),Gh=V(Je,Je.SIZE),Ml=V(Je,Je.COORDINATE),po=V(Je,Je.VIEWPORT);po.zw;po.xy;const Ro=(o=0)=>Ii("uv"+(o>0?o:""),"vec2");class Bv extends re{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const ar=U(Bv).setParameterLength(1,2),jg=new St;class br extends Eo{static get type(){return"TextureNode"}constructor(e=jg,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ue.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===Xe?"uvec4":this.value.type===Et?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Ro(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=Q(this.value.matrix)),this._matrixUniform.mul(I(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?ue.OBJECT:ue.NONE,this}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.image instanceof ImageBitmap&&s.flipY===!0||s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0||s.isDepthTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(ke(ar(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||s.isTexture!==!0)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;(i===null||e.context.forceUVContext===!0)&&e.context.getUV&&(i=e.context.getUV(this,e)),i||(i=this.getDefaultUV()),this.updateMatrix===!0&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let n=this.levelNode;n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=n,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateSnippet(e,t,s,i,n,r,a,l){const c=this.value;let h;return i?h=e.generateTextureLevel(c,t,s,i,r):n?h=e.generateTextureBias(c,t,s,n,r):l?h=e.generateTextureGrad(c,t,s,l,r):a?h=e.generateTextureCompare(c,t,s,a,r):this.sampler===!1?h=e.generateTextureLoad(c,t,s,r):h=e.generateTexture(c,t,s,r),h}generate(e,t){const s=this.value,i=e.getNodeProperties(this),n=super.generate(e,"property");if(/^sampler/.test(t))return n+"_sampler";if(e.isReference(t))return n;{const r=e.getDataFromNode(this);let a=r.propertyName;if(a===void 0){const{uvNode:h,levelNode:u,biasNode:d,compareNode:p,depthNode:f,gradNode:m}=i,x=this.generateUV(e,h),g=u?u.build(e,"float"):null,_=d?d.build(e,"float"):null,b=f?f.build(e,"int"):null,T=p?p.build(e,"float"):null,S=m?[m[0].build(e,"vec2"),m[1].build(e,"vec2")]:null,C=e.getVarFromNode(this);a=e.getPropertyName(C);const w=this.generateSnippet(e,n,x,g,_,b,T,S);e.addLineFlowCode(`${a} = ${w}`,this),r.snippet=w,r.propertyName=a}let l=a;const c=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(l=Nu(mr(l,c),s.colorSpace).setup(e).build(e,c)),e.format(l,c,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=k(e),t.referenceNode=this.getSelf(),k(t)}blur(e){const t=this.clone();t.biasNode=k(e).mul(Fv(t)),t.referenceNode=this.getSelf();const s=t.value;return t.generateMipmaps===!1&&(s&&s.generateMipmaps===!1||s.minFilter===ut||s.magFilter===ut)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),k(t)}level(e){const t=this.clone();return t.levelNode=k(e),t.referenceNode=this.getSelf(),k(t)}size(e){return ar(this,e)}bias(e){const t=this.clone();return t.biasNode=k(e),t.referenceNode=this.getSelf(),k(t)}compare(e){const t=this.clone();return t.compareNode=k(e),t.referenceNode=this.getSelf(),k(t)}grad(e,t){const s=this.clone();return s.gradNode=[k(e),k(t)],s.referenceNode=this.getSelf(),k(s)}depth(e){const t=this.clone();return t.depthNode=k(e),t.referenceNode=this.getSelf(),k(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}const Iv=U(br).setParameterLength(1,4).setName("texture"),_e=(o=jg,e=null,t=null,s=null)=>{let i;return o&&o.isTextureNode===!0?(i=k(o.clone()),i.referenceNode=o.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=Iv(o,e,t,s),i},xs=(...o)=>_e(...o).setSampler(!1);class Lv extends St{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ut,this.minFilter=ut,this.generateMipmaps=!1,this.needsUpdate=!0}}const Or=new he;class qg extends br{static get type(){return"ViewportTextureNode"}constructor(e=or,t=null,s=null){s===null&&(s=new Lv,s.minFilter=ei),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=ue.FRAME}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Or);const s=this.value;(s.image.width!==Or.width||s.image.height!==Or.height)&&(s.image.width=Or.width,s.image.height=Or.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Yg=U(qg,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let ic=null;class Uv extends qg{static get type(){return"ViewportDepthTextureNode"}constructor(e=or,t=null){ic===null&&(ic=new Is),super(e,t,ic)}}const kv=U(Uv).setParameterLength(0,2);class kt extends re{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===kt.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===kt.DEPTH_BASE)s!==null&&(i=Kg().assign(s));else if(t===kt.DEPTH)e.isPerspectiveCamera?i=zv(st.z,rn,on):i=fo(st.z,rn,on);else if(t===kt.LINEAR_DEPTH)if(s!==null)if(e.isPerspectiveCamera){const n=Xg(s,rn,on);i=fo(n,rn,on)}else i=s;else i=fo(st.z,rn,on);return i}}kt.DEPTH_BASE="depthBase";kt.DEPTH="depth";kt.LINEAR_DEPTH="linearDepth";const fo=(o,e,t)=>o.add(e).div(e.sub(t)),zv=(o,e,t)=>e.add(o).mul(t).div(t.sub(e).mul(o)),Xg=(o,e,t)=>e.mul(t).div(t.sub(e).mul(o).sub(t)),Zg=(o,e,t)=>{e=e.max(1e-6).toVar();const s=ii(o.negate().div(e)),i=ii(t.div(e));return s.div(i)},Kg=U(kt,kt.DEPTH_BASE),Qg=V(kt,kt.DEPTH),Gv=U(kt,kt.LINEAR_DEPTH).setParameterLength(0,1);kv();Qg.assign=o=>Kg(o);const nc=new N,Vv=new N,Hv=new Ht;class Mi{constructor(e=new N(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,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=nc.subVectors(s,t).cross(Vv.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const 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){const s=e.delta(nc),i=this.normal.dot(s);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/i;return n<0||n>1?null:t.copy(e.start).addScaledVector(s,n)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<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){const s=t||Hv.getNormalMatrix(e),i=this.coplanarPoint(nc).applyMatrix4(e),n=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(n),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)}}class fn extends pn{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Qt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new ge(0,0,e,t),this.scissorTest=!1,this.viewport=new ge(0,0,e,t);const i={width:e,height:t,depth:s.depth},n=new St(i);this.textures=[];const r=s.count;for(let a=0;a<r;a++)this.textures[a]=n.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:Qt,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 s=0;s<this.textures.length;s++)this.textures[s].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,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,n=this.textures.length;i<n;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,this.textures[i].isArrayTexture=this.textures[i].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,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const i=Object.assign({},e.textures[t].image);this.textures[t].source=new pu(i)}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}dispose(){this.dispatchEvent({type:"dispose"})}}new Mi;new N;new N;new N;new Ie;new N(0,0,-1);new ge;new N;new N;new ge;new he;const Wv=new fn;or.flipX();Wv.depthTexture=new Is(1,1);let $v=0;class Vt extends pn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:$v++}),this.uuid=Ks(),this.name="",this.type="Material",this.blending=Js,this.side=Qs,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Ya,this.blendDst=Xa,this.blendEquation=bs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new ve(0,0,0),this.blendAlpha=0,this.depthFunc=Za,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Oh,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=en,this.stencilZFail=en,this.stencilZPass=en,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(const t in e){const s=e[t];if(s===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(s.dispersion=this.dispersion),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapRotation!==void 0&&(s.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==Js&&(s.blending=this.blending),this.side!==Qs&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==Ya&&(s.blendSrc=this.blendSrc),this.blendDst!==Xa&&(s.blendDst=this.blendDst),this.blendEquation!==bs&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==Za&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Oh&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==en&&(s.stencilFail=this.stencilFail),this.stencilZFail!==en&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==en&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function i(n){const r=[];for(const a in n){const l=n[a];delete l.metadata,r.push(l)}return r}if(t){const n=i(e.textures),r=i(e.images);n.length>0&&(s.textures=n),r.length>0&&(s.images=r)}return s}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;const t=e.clippingPlanes;let s=null;if(t!==null){const i=t.length;s=new Array(i);for(let n=0;n!==i;++n)s[n]=t[n].clone()}return this.clippingPlanes=s,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.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++}}const gp=new us,rc=new Ie,jv=Q(0).onReference(({material:o})=>o).onObjectUpdate(({material:o})=>o.refractionRatio),oc=Q(1).onReference(({material:o})=>o).onObjectUpdate(function({material:o,scene:e}){return o.envMap?o.envMapIntensity:e.environmentIntensity}),Jg=Q(new Ie).onReference(function(o){return o.material}).onObjectUpdate(function({material:o,scene:e}){const t=e.environment!==null&&o.envMap===null?e.environmentRotation:o.envMapRotation;return t?(gp.copy(t),rc.makeRotationFromEuler(gp)):rc.identity(),rc}),qv=je.negate().reflect(et),Yv=je.negate().refract(et,jv),Xv=qv.transformDirection(hi).toVar("reflectVector"),Zv=Yv.transformDirection(hi).toVar("reflectVector");class Cl extends St{constructor(e=[],t=xo,s,i,n,r,a,l,c,h){super(e,t,s,i,n,r,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}const Kv=new Cl;class Qv extends br{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===xo?Xv:e.mapping===Ka?Zv:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),I(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return(e.renderer.coordinateSystem===Oi||!s.isRenderTargetTexture)&&(t=I(t.x.negate(),t.yz)),Jg.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const Jv=U(Qv).setParameterLength(1,4).setName("cubeTexture"),wo=(o=Kv,e=null,t=null,s=null)=>{let i;return o&&o.isCubeTextureNode===!0?(i=k(o.clone()),i.referenceNode=o.getSelf(),e!==null&&(i.uvNode=k(e)),t!==null&&(i.levelNode=k(t)),s!==null&&(i.biasNode=k(s))):i=Jv(o,e,t,s),i};class ew extends Co{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Lu extends re{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=ue.OBJECT}element(e){return k(new ew(this,k(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;this.count!==null?t=kg(null,e,this.count):Array.isArray(this.getValueFromReference())?t=Os(null,e):e==="texture"?t=_e(null):e==="cubeTexture"?t=wo(null):t=Q(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let i=1;i<t.length;i++)s=s[t[i]];return s}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Be=(o,e,t)=>k(new Lu(o,e,t)),yp=(o,e,t,s)=>k(new Lu(o,e,s,t));class tw extends Lu{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}}const Ei=(o,e,t=null)=>k(new tw(o,e,t)),ey=L(o=>(o.geometry.hasAttribute("tangent")===!1&&o.geometry.computeTangents(),Ii("tangent","vec4")))(),Uu=ey.xyz.toVar("tangentLocal"),ty=Sl.mul(ne(Uu,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),sw=L(([o,e],t)=>{let s=o.mul(ey.w).xyz;return t.material.flatShading!==!0&&(s=ws(s,e)),s}).once(),iw=sw(zs.cross(ty),"v_bitangentView").normalize().toVar("bitangentView"),so=Ft(ty,iw,zs),nw=(()=>{let o=rr.cross(je);return o=o.cross(rr).normalize(),o=Ge(o,et,tn.mul(Xs.oneMinus()).oneMinus().pow2().pow2()).normalize(),o})(),rw=L(o=>{const{eye_pos:e,surf_norm:t,mapN:s,uv:i}=o,n=e.dFdx(),r=e.dFdy(),a=i.dFdx(),l=i.dFdy(),c=t,h=r.cross(c),u=c.cross(n),d=h.mul(a.x).add(u.mul(l.x)),p=h.mul(a.y).add(u.mul(l.y)),f=d.dot(d).max(p.dot(p)),m=wl.mul(f.inverseSqrt());return Dt(d.mul(s.x,m),p.mul(s.y,m),c.mul(s.z)).normalize()});class ow extends nt{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Di}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);s!==null&&(i=I(i.xy.mul(s),i.z));let n=null;return t===H_?n=Wg(i):t===Di&&(e.hasGeometryAttribute("tangent")===!0?n=so.mul(i).normalize():n=rw({eye_pos:st,surf_norm:zs,mapN:i,uv:Ro()})),n}}const xp=U(ow).setParameterLength(1,2),aw=L(({textureNode:o,bumpScale:e})=>{const t=i=>o.cache().context({getUV:n=>i(n.uvNode||Ro()),forceUVContext:!0}),s=B(t(i=>i));return H(B(t(i=>i.add(i.dFdx()))).sub(s),B(t(i=>i.add(i.dFdy()))).sub(s)).mul(e)}),lw=L(o=>{const{surf_pos:e,surf_norm:t,dHdxy:s}=o,i=e.dFdx().normalize(),n=e.dFdy().normalize(),r=t,a=n.cross(r),l=r.cross(i),c=i.dot(a).mul(wl),h=c.sign().mul(s.x.mul(a).add(s.y.mul(l)));return c.abs().mul(t).sub(h).normalize()});class cw extends nt{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=this.scaleNode!==null?this.scaleNode:1,t=aw({textureNode:this.textureNode,bumpScale:e});return lw({surf_pos:st,surf_norm:zs,dHdxy:t})}}const hw=U(cw).setParameterLength(1,2),_p=new Map;class D extends re{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=_p.get(e);return s===void 0&&(s=Ei(e,t),_p.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===D.COLOR){const n=t.color!==void 0?this.getColor(s):I();t.map&&t.map.isTexture===!0?i=n.mul(this.getTexture("map")):i=n}else if(s===D.OPACITY){const n=this.getFloat(s);t.alphaMap&&t.alphaMap.isTexture===!0?i=n.mul(this.getTexture("alpha")):i=n}else if(s===D.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=B(1);else if(s===D.SPECULAR_INTENSITY){const n=this.getFloat(s);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n}else if(s===D.SPECULAR_COLOR){const n=this.getColor(s);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=n.mul(this.getTexture(s).rgb):i=n}else if(s===D.ROUGHNESS){const n=this.getFloat(s);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.METALNESS){const n=this.getFloat(s);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=n.mul(this.getTexture(s).b):i=n}else if(s===D.EMISSIVE){const n=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(n);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=r.mul(this.getTexture(s)):i=r}else if(s===D.NORMAL)t.normalMap?(i=xp(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):t.bumpMap?i=hw(this.getTexture("bump").r,this.getFloat("bumpScale")):i=zs;else if(s===D.CLEARCOAT){const n=this.getFloat(s);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.CLEARCOAT_ROUGHNESS){const n=this.getFloat(s);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=xp(this.getTexture(s),this.getCache(s+"Scale","vec2")):i=zs;else if(s===D.SHEEN){const n=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=n.mul(this.getTexture("sheenColor").rgb):i=n}else if(s===D.SHEEN_ROUGHNESS){const n=this.getFloat(s);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=n.mul(this.getTexture(s).a):i=n,i=i.clamp(.07,1)}else if(s===D.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const n=this.getTexture(s);i=bu(Br.x,Br.y,Br.y.negate(),Br.x).mul(n.rg.mul(2).sub(H(1)).normalize().mul(n.b))}else i=Br;else if(s===D.IRIDESCENCE_THICKNESS){const n=Be("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Be("0","float",t.iridescenceThicknessRange);i=n.sub(r).mul(this.getTexture(s).g).add(r)}else i=n}else if(s===D.TRANSMISSION){const n=this.getFloat(s);t.transmissionMap?i=n.mul(this.getTexture(s).r):i=n}else if(s===D.THICKNESS){const n=this.getFloat(s);t.thicknessMap?i=n.mul(this.getTexture(s).g):i=n}else if(s===D.IOR)i=this.getFloat(s);else if(s===D.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===D.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===D.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):B(0);else{const n=this.getNodeType(e);i=this.getCache(s,n)}return i}}D.ALPHA_TEST="alphaTest";D.COLOR="color";D.OPACITY="opacity";D.SHININESS="shininess";D.SPECULAR="specular";D.SPECULAR_STRENGTH="specularStrength";D.SPECULAR_INTENSITY="specularIntensity";D.SPECULAR_COLOR="specularColor";D.REFLECTIVITY="reflectivity";D.ROUGHNESS="roughness";D.METALNESS="metalness";D.NORMAL="normal";D.CLEARCOAT="clearcoat";D.CLEARCOAT_ROUGHNESS="clearcoatRoughness";D.CLEARCOAT_NORMAL="clearcoatNormal";D.EMISSIVE="emissive";D.ROTATION="rotation";D.SHEEN="sheen";D.SHEEN_ROUGHNESS="sheenRoughness";D.ANISOTROPY="anisotropy";D.IRIDESCENCE="iridescence";D.IRIDESCENCE_IOR="iridescenceIOR";D.IRIDESCENCE_THICKNESS="iridescenceThickness";D.IOR="ior";D.TRANSMISSION="transmission";D.THICKNESS="thickness";D.ATTENUATION_DISTANCE="attenuationDistance";D.ATTENUATION_COLOR="attenuationColor";D.LINE_SCALE="scale";D.LINE_DASH_SIZE="dashSize";D.LINE_GAP_SIZE="gapSize";D.LINE_WIDTH="linewidth";D.LINE_DASH_OFFSET="dashOffset";D.POINT_SIZE="size";D.DISPERSION="dispersion";D.LIGHT_MAP="light";D.AO="ao";const uw=V(D,D.ALPHA_TEST),dw=V(D,D.COLOR),pw=V(D,D.SHININESS),fw=V(D,D.EMISSIVE),sy=V(D,D.OPACITY),mw=V(D,D.SPECULAR),bp=V(D,D.SPECULAR_INTENSITY),gw=V(D,D.SPECULAR_COLOR),ka=V(D,D.SPECULAR_STRENGTH),ac=V(D,D.REFLECTIVITY),yw=V(D,D.ROUGHNESS),xw=V(D,D.METALNESS),_w=V(D,D.NORMAL),bw=V(D,D.CLEARCOAT),Tw=V(D,D.CLEARCOAT_ROUGHNESS),Sw=V(D,D.CLEARCOAT_NORMAL),vw=V(D,D.ROTATION),ww=V(D,D.SHEEN),Mw=V(D,D.SHEEN_ROUGHNESS),Cw=V(D,D.ANISOTROPY),Ew=V(D,D.IRIDESCENCE),Aw=V(D,D.IRIDESCENCE_IOR),Rw=V(D,D.IRIDESCENCE_THICKNESS),Nw=V(D,D.TRANSMISSION),Pw=V(D,D.THICKNESS),Fw=V(D,D.IOR),Dw=V(D,D.ATTENUATION_DISTANCE),Ow=V(D,D.ATTENUATION_COLOR),Bw=V(D,D.LINE_SCALE),Iw=V(D,D.LINE_DASH_SIZE),Lw=V(D,D.LINE_GAP_SIZE);D.LINE_WIDTH;const Uw=V(D,D.LINE_DASH_OFFSET),kw=V(D,D.POINT_SIZE),zw=V(D,D.DISPERSION),iy=V(D,D.LIGHT_MAP),Gw=V(D,D.AO),Br=Q(new he).onReference(function(o){return o.material}).onRenderUpdate(function({material:o}){this.value.set(o.anisotropy*Math.cos(o.anisotropyRotation),o.anisotropy*Math.sin(o.anisotropyRotation))}),ny=L(o=>o.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Vw extends Bg{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class Hw extends ls{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}class Ww extends re{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ue.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:s,instanceColor:i}=this;let{instanceMatrixNode:n,instanceColorNode:r}=this;if(n===null){if(t<=1e3)n=kg(s.array,"mat4",Math.max(t,1)).element(Du);else{const l=new Vw(s.array,16,1);this.buffer=l;const c=s.usage===qn?up:hp,h=[c(l,"vec4",16,0),c(l,"vec4",16,4),c(l,"vec4",16,8),c(l,"vec4",16,12)];n=nr(...h)}this.instanceMatrixNode=n}if(i&&r===null){const l=new Hw(i.array,3),c=i.usage===qn?up:hp;this.bufferColor=l,r=I(c(l,"vec3",3,0)),this.instanceColorNode=r}const a=n.mul(bt).xyz;if(bt.assign(a),e.hasGeometryAttribute("normal")){const l=Av(ks,n);ks.assign(l)}this.instanceColorNode!==null&&nl("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==qn&&this.buffer!==null&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==qn&&this.bufferColor!==null&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class $w extends Ww{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const jw=U($w).setParameterLength(1);class qw extends re{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){this.batchingIdNode===null&&(e.getDrawIndex()===null?this.batchingIdNode=Du:this.batchingIdNode=uv);const s=L(([f])=>{const m=ke(ar(xs(this.batchMesh._indirectTexture),0).x),x=ke(f).mod(m),g=ke(f).div(m);return xs(this.batchMesh._indirectTexture,qs(x,g)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(ke(this.batchingIdNode)),i=this.batchMesh._matricesTexture,n=ke(ar(xs(i),0).x),r=B(s).mul(4).toInt().toVar(),a=r.mod(n),l=r.div(n),c=nr(xs(i,qs(a,l)),xs(i,qs(a.add(1),l)),xs(i,qs(a.add(2),l)),xs(i,qs(a.add(3),l))),h=this.batchMesh._colorsTexture;if(h!==null){const m=L(([x])=>{const g=ke(ar(xs(h),0).x),_=x,b=_.mod(g),T=_.div(g);return xs(h,qs(b,T)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(s);nl("vec3","vBatchColor").assign(m)}const u=Ft(c);bt.assign(c.mul(bt));const d=ks.div(I(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),p=u.mul(d).xyz;ks.assign(p),e.hasGeometryAttribute("tangent")&&Uu.mulAssign(u)}}const Yw=U(qw).setParameterLength(1),Tp=new WeakMap;class Xw extends re{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ue.OBJECT,this.skinIndexNode=Ii("skinIndex","uvec4"),this.skinWeightNode=Ii("skinWeight","vec4"),this.bindMatrixNode=Be("bindMatrix","mat4"),this.bindMatrixInverseNode=Be("bindMatrixInverse","mat4"),this.boneMatricesNode=yp("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=bt,this.toPositionNode=bt,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,a=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w),u=n.mul(t),d=Dt(a.mul(i.x).mul(u),l.mul(i.y).mul(u),c.mul(i.z).mul(u),h.mul(i.w).mul(u));return r.mul(d).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=ks){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:n,bindMatrixInverseNode:r}=this,a=e.element(s.x),l=e.element(s.y),c=e.element(s.z),h=e.element(s.w);let u=Dt(i.x.mul(a),i.y.mul(l),i.z.mul(c),i.w.mul(h));return u=r.mul(u).mul(n),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=yp("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,mp)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||Km(e.object).useVelocity===!0}setup(e){this.needsPreviousBoneMatrices(e)&&mp.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const s=this.getSkinnedNormal();ks.assign(s),e.hasGeometryAttribute("tangent")&&Uu.assign(s)}return t}generate(e,t){if(t!=="void")return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Tp.get(t)!==e.frameId&&(Tp.set(t,e.frameId),this.previousBoneMatricesNode!==null&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const Zw=o=>k(new Xw(o));class Kw extends St{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=ut,this.minFilter=ut,this.wrapR=Ri,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}const lc=new WeakMap,jt=new ge,Sp=L(({bufferMap:o,influence:e,stride:t,width:s,depth:i,offset:n})=>{const r=ke(hv).mul(t).add(n),a=r.div(s),l=r.sub(a.mul(s));return xs(o,qs(l,a)).depth(i).xyz.mul(e)});function Qw(o){const e=o.morphAttributes.position!==void 0,t=o.morphAttributes.normal!==void 0,s=o.morphAttributes.color!==void 0,i=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,n=i!==void 0?i.length:0;let r=lc.get(o);if(r===void 0||r.count!==n){let g=function(){m.dispose(),lc.delete(o),o.removeEventListener("dispose",g)};r!==void 0&&r.texture.dispose();const a=o.morphAttributes.position||[],l=o.morphAttributes.normal||[],c=o.morphAttributes.color||[];let h=0;e===!0&&(h=1),t===!0&&(h=2),s===!0&&(h=3);let u=o.attributes.position.count*h,d=1;const p=4096;u>p&&(d=Math.ceil(u/p),u=p);const f=new Float32Array(u*d*4*n),m=new Kw(f,u,d,n);m.type=Kt,m.needsUpdate=!0;const x=h*4;for(let _=0;_<n;_++){const b=a[_],T=l[_],S=c[_],C=u*d*4*_;for(let w=0;w<b.count;w++){const R=w*x;e===!0&&(jt.fromBufferAttribute(b,w),f[C+R+0]=jt.x,f[C+R+1]=jt.y,f[C+R+2]=jt.z,f[C+R+3]=0),t===!0&&(jt.fromBufferAttribute(T,w),f[C+R+4]=jt.x,f[C+R+5]=jt.y,f[C+R+6]=jt.z,f[C+R+7]=0),s===!0&&(jt.fromBufferAttribute(S,w),f[C+R+8]=jt.x,f[C+R+9]=jt.y,f[C+R+10]=jt.z,f[C+R+11]=S.itemSize===4?jt.w:1)}}r={count:n,texture:m,stride:h,size:new he(u,d)},lc.set(o,r),o.addEventListener("dispose",g)}return r}class Jw extends re{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Q(1),this.updateType=ue.OBJECT}setup(e){const{geometry:t}=e,s=t.morphAttributes.position!==void 0,i=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,n=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,r=n!==void 0?n.length:0,{texture:a,stride:l,size:c}=Qw(t);s===!0&&bt.mulAssign(this.morphBaseInfluence),i===!0&&ks.mulAssign(this.morphBaseInfluence);const h=ke(c.width);Ts(r,({i:u})=>{const d=B(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?d.assign(xs(this.mesh.morphTexture,qs(ke(u).add(1),ke(Du))).r):d.assign(Be("morphTargetInfluences","float").element(u).toVar()),Ze(d.notEqual(0),()=>{s===!0&&bt.addAssign(Sp({bufferMap:a,influence:d,stride:l,width:h,depth:u,offset:ke(0)})),i===!0&&ks.addAssign(Sp({bufferMap:a,influence:d,stride:l,width:h,depth:u,offset:ke(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((t,s)=>t+s,0)}}const eM=U(Jw).setParameterLength(1);class Tr extends re{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class tM extends Tr{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class sM extends Fg{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s=I().toVar("directDiffuse"),i=I().toVar("directSpecular"),n=I().toVar("indirectDiffuse"),r=I().toVar("indirectSpecular"),a={directDiffuse:s,directSpecular:i,indirectDiffuse:n,indirectSpecular:r};return{radiance:I().toVar("radiance"),irradiance:I().toVar("irradiance"),iblIrradiance:I().toVar("iblIrradiance"),ambientOcclusion:B(1).toVar("ambientOcclusion"),reflectedLight:a,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const iM=U(sM);class nM extends Tr{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}class cs extends re{static get type(){return"ClippingNode"}constructor(e=cs.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===cs.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===cs.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return L(()=>{const s=B().toVar("distanceToPlane"),i=B().toVar("distanceToGradient"),n=B(1).toVar("clipOpacity"),r=t.length;if(this.hardwareClipping===!1&&r>0){const l=Os(t);Ts(r,({i:c})=>{const h=l.element(c);s.assign(st.dot(h.xyz).negate().add(h.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Bi(i.negate(),i,s))})}const a=e.length;if(a>0){const l=Os(e),c=B(1).toVar("intersectionClipOpacity");Ts(a,({i:h})=>{const u=l.element(h);s.assign(st.dot(u.xyz).negate().add(u.w)),i.assign(s.fwidth().div(2)),c.mulAssign(Bi(i.negate(),i,s).oneMinus())}),n.mulAssign(c.oneMinus())}Se.a.mulAssign(n),Se.a.equal(0).discard()})()}setupDefault(e,t){return L(()=>{const s=t.length;if(this.hardwareClipping===!1&&s>0){const n=Os(t);Ts(s,({i:r})=>{const a=n.element(r);st.dot(a.xyz).greaterThan(a.w).discard()})}const i=e.length;if(i>0){const n=Os(e),r=_u(!0).toVar("clipped");Ts(i,({i:a})=>{const l=n.element(a);r.assign(st.dot(l.xyz).greaterThan(l.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),L(()=>{const i=Os(e),n=Tl(t.getClipDistance());Ts(s,({i:r})=>{const a=i.element(r),l=st.dot(a.xyz).sub(a.w).negate();n.element(r).assign(l)})})()}}cs.ALPHA_TO_COVERAGE="alphaToCoverage";cs.DEFAULT="default";cs.HARDWARE="hardware";const rM=()=>k(new cs),oM=()=>k(new cs(cs.ALPHA_TO_COVERAGE)),aM=()=>k(new cs(cs.HARDWARE)),lM=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class cM{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=lM,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:s,material:i,object:n}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:n.matrixWorld.clone()},n.center&&(t.center=n.center.clone()),n.morphTargetInfluences&&(t.morphTargetInfluences=n.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:a}=e.context;t.bufferWidth=r,t.bufferHeight=a}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={version:i.version}}return t}containsNode(e){const t=e.material;for(const s in t)if(t[s]&&t[s].isNode)return!0;return e.renderer.overrideNodes.modelViewMatrix!==null||e.renderer.overrideNodes.modelNormalViewMatrix!==null}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];i!=null&&(typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e){const{object:t,material:s,geometry:i}=e,n=this.getRenderObjectData(e);if(n.worldMatrix.equals(t.matrixWorld)!==!0)return n.worldMatrix.copy(t.matrixWorld),!1;const r=n.material;for(const m in r){const x=r[m],g=s[m];if(x.equals!==void 0){if(x.equals(g)===!1)return x.copy(g),!1}else if(g.isTexture===!0){if(x.id!==g.id||x.version!==g.version)return x.id=g.id,x.version=g.version,!1}else if(x!==g)return r[m]=g,!1}if(r.transmission>0){const{width:m,height:x}=e.context;if(n.bufferWidth!==m||n.bufferHeight!==x)return n.bufferWidth=m,n.bufferHeight=x,!1}const a=n.geometry,l=i.attributes,c=a.attributes,h=Object.keys(c),u=Object.keys(l);if(a.id!==i.id)return a.id=i.id,!1;if(h.length!==u.length)return n.geometry.attributes=this.getAttributesData(l),!1;for(const m of h){const x=c[m],g=l[m];if(g===void 0)return delete c[m],!1;if(x.version!==g.version)return x.version=g.version,!1}const d=i.index,p=a.indexVersion,f=d?d.version:null;if(p!==f)return a.indexVersion=f,!1;if(a.drawRange.start!==i.drawRange.start||a.drawRange.count!==i.drawRange.count)return a.drawRange.start=i.drawRange.start,a.drawRange.count=i.drawRange.count,!1;if(n.morphTargetInfluences){let m=!1;for(let x=0;x<n.morphTargetInfluences.length;x++)n.morphTargetInfluences[x]!==t.morphTargetInfluences[x]&&(m=!0);if(m)return!0}return n.center&&n.center.equals(t.center)===!1?(n.center.copy(t.center),!0):(e.bundle!==null&&(n.version=e.bundle.version),!0)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=e.object.static===!0,n=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;return i||n?!1:this.equals(e)!==!0}}const hM=.05,vp=L(([o])=>Ui(fe(1e4,_s(fe(17,o.x).add(fe(.1,o.y)))).mul(Dt(.1,ns(_s(fe(13,o.y).add(o.x))))))),wp=L(([o])=>vp(H(vp(o.xy),o.z))),uM=L(([o])=>{const e=vt(ni(wg(o.xyz)),ni(Mg(o.xyz))),t=B(1).div(B(hM).mul(e)).toVar("pixScale"),s=H(To(un(ii(t))),To(Mu(ii(t)))),i=H(wp(un(s.x.mul(o.xyz))),wp(un(s.y.mul(o.xyz)))),n=Ui(ii(t)),r=Dt(fe(n.oneMinus(),i.x),fe(n,i.y)),a=fr(n,n.oneMinus()),l=I(r.mul(r).div(fe(2,a).mul(At(1,a))),r.sub(fe(.5,a)).div(At(1,a)),At(1,At(1,r).mul(At(1,r)).div(fe(2,a).mul(At(1,a))))),c=r.lessThan(a.oneMinus()).select(r.lessThan(a).select(l.x,l.y),l.z);return ai(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class dM extends Lg{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e),s=e.hasGeometryAttribute(t);let i;return s===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new ge(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const pM=(o=0)=>k(new dM(o));class it extends Vt{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Xm(this)}build(e){this.setup(e)}setupObserver(e){return new cM(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),n=this.vertexNode||i;e.stack.outputNode=n,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let r;const a=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(s!==null?s.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupVariants(e);const l=this.setupLighting(e);a!==null&&e.stack.add(a);const c=ne(l,Se.a).max(0);r=this.setupOutput(e,c),uo.assign(r);const h=this.outputNode!==null;if(h&&(r=this.outputNode),s!==null){const u=t.getMRT(),d=this.mrtNode;u!==null?(h&&uo.assign(r),r=u,d!==null&&(r=u.merge(d))):d!==null&&(r=d)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=ne(l)),r=this.setupOutput(e,l)}e.stack.outputNode=r,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const n=e.renderer.samples;this.alphaToCoverage&&n>1?i=oM():e.stack.add(rM())}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.add(aM()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(i===null){const n=t.getMRT();n&&n.has("depth")?i=n.get("depth"):t.logarithmicDepthBuffer===!0&&(s.isPerspectiveCamera?i=Zg(st.z,rn,on):i=fo(st.z,rn,on))}i!==null&&Qg.assign(i).toStack()}setupPositionView(){return Sl.mul(bt).xyz}setupModelViewProjection(){return Ou.mul(st)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),ny}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&eM(t).toStack(),t.isSkinnedMesh===!0&&Zw(t).toStack(),this.displacementMap){const i=Ei("displacementMap","texture"),n=Ei("displacementScale","float"),r=Ei("displacementBias","float");bt.addAssign(ks.normalize().mul(i.x.mul(n).add(r)))}return t.isBatchedMesh&&Yw(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&jw(t).toStack(),this.positionNode!==null&&bt.assign(ev(this.positionNode,"POSITION")),bt}setupDiffuseColor({object:e,geometry:t}){this.maskNode!==null&&_u(this.maskNode).not().discard();let s=this.colorNode?ne(this.colorNode):dw;this.vertexColors===!0&&t.hasAttribute("color")&&(s=s.mul(pM())),e.instanceColor&&(s=nl("vec3","vInstanceColor").mul(s)),e.isBatchedMesh&&e._colorsTexture&&(s=nl("vec3","vBatchColor").mul(s)),Se.assign(s);const i=this.opacityNode?B(this.opacityNode):sy;Se.a.assign(Se.a.mul(i));let n=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(n=this.alphaTestNode!==null?B(this.alphaTestNode):uw,Se.a.lessThanEqual(n).discard()),this.alphaHash===!0&&Se.a.lessThan(uM(bt)).discard(),this.transparent===!1&&this.blending===Js&&this.alphaToCoverage===!1?Se.a.assign(1):n===null&&Se.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return this.lights===!0?I(0):Se.rgb}setupNormal(){return this.normalNode?I(this.normalNode):_w}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ei("envMap","cubeTexture"):Ei("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new nM(iy)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),this.aoNode!==null||e.material.aoMap){const r=this.aoNode!==null?this.aoNode:Gw;t.push(new tM(r))}let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:n}=this,a=this.lights===!0||this.lightsNode!==null?this.setupLights(e):null;let l=this.setupOutgoingLight(e);if(a&&a.getScope().hasLights){const c=this.setupLightingModel(e)||null;l=iM(a,c,s,i)}else s!==null&&(l=I(i!==null?Ge(l,s,i):s));return(n&&n.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(lp.assign(I(n||fw)),l=l.add(lp)),l}setupFog(e,t){const s=e.fogNode;return s&&(uo.assign(t),t=ne(s)),t}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),t}setDefaultValues(e){for(const s in e){const i=e[s];this[s]===void 0&&(this[s]=i,i&&i.clone&&(this[s]=i.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const s in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,s)===void 0&&t[s].get!==void 0&&Object.defineProperty(this.constructor.prototype,s,t[s])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const s=Vt.prototype.toJSON.call(this,e),i=tl(this);s.inputNodes={};for(const{property:r,childNode:a}of i)s.inputNodes[r]=a.toJSON(e).uuid;function n(r){const a=[];for(const l in r){const c=r[l];delete c.metadata,a.push(c)}return a}if(t){const r=n(e.textures),a=n(e.images),l=n(e.nodes);r.length>0&&(s.textures=r),a.length>0&&(s.images=a),l.length>0&&(s.nodes=l)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}let fM=0;const es=new Ie,cc=new dt,Pn=new N,qt=new Ao,Ir=new Ao,pt=new N;class ui extends pn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:fM++}),this.uuid=Ks(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,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(qm(e)?Jm:Qm)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,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,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(s!==void 0){const n=new Ht().getNormalMatrix(e);s.applyNormalMatrix(n),s.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return es.makeRotationFromQuaternion(e),this.applyMatrix4(es),this}rotateX(e){return es.makeRotationX(e),this.applyMatrix4(es),this}rotateY(e){return es.makeRotationY(e),this.applyMatrix4(es),this}rotateZ(e){return es.makeRotationZ(e),this.applyMatrix4(es),this}translate(e,t,s){return es.makeTranslation(e,t,s),this.applyMatrix4(es),this}scale(e,t,s){return es.makeScale(e,t,s),this.applyMatrix4(es),this}lookAt(e){return cc.lookAt(e),cc.updateMatrix(),this.applyMatrix4(cc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Pn).negate(),this.translate(Pn.x,Pn.y,Pn.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const s=[];for(let i=0,n=e.length;i<n;i++){const r=e[i];s.push(r.x,r.y,r.z||0)}this.setAttribute("position",new Pt(s,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.count&&console.warn("THREE.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 Ao);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let s=0,i=t.length;s<i;s++){const n=t[s];qt.setFromBufferAttribute(n),this.morphTargetsRelative?(pt.addVectors(this.boundingBox.min,qt.min),this.boundingBox.expandByPoint(pt),pt.addVectors(this.boundingBox.max,qt.max),this.boundingBox.expandByPoint(pt)):(this.boundingBox.expandByPoint(qt.min),this.boundingBox.expandByPoint(qt.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.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 bl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new N,1/0);return}if(e){const s=this.boundingSphere.center;if(qt.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n<r;n++){const a=t[n];Ir.setFromBufferAttribute(a),this.morphTargetsRelative?(pt.addVectors(qt.min,Ir.min),qt.expandByPoint(pt),pt.addVectors(qt.max,Ir.max),qt.expandByPoint(pt)):(qt.expandByPoint(Ir.min),qt.expandByPoint(Ir.max))}qt.getCenter(s);let i=0;for(let n=0,r=e.count;n<r;n++)pt.fromBufferAttribute(e,n),i=Math.max(i,s.distanceToSquared(pt));if(t)for(let n=0,r=t.length;n<r;n++){const a=t[n],l=this.morphTargetsRelative;for(let c=0,h=a.count;c<h;c++)pt.fromBufferAttribute(a,c),l&&(Pn.fromBufferAttribute(e,c),pt.add(Pn)),i=Math.max(i,s.distanceToSquared(pt))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const s=t.position,i=t.normal,n=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ls(new Float32Array(4*s.count),4));const r=this.getAttribute("tangent"),a=[],l=[];for(let R=0;R<s.count;R++)a[R]=new N,l[R]=new N;const c=new N,h=new N,u=new N,d=new he,p=new he,f=new he,m=new N,x=new N;function g(R,P,z){c.fromBufferAttribute(s,R),h.fromBufferAttribute(s,P),u.fromBufferAttribute(s,z),d.fromBufferAttribute(n,R),p.fromBufferAttribute(n,P),f.fromBufferAttribute(n,z),h.sub(c),u.sub(c),p.sub(d),f.sub(d);const $=1/(p.x*f.y-f.x*p.y);isFinite($)&&(m.copy(h).multiplyScalar(f.y).addScaledVector(u,-p.y).multiplyScalar($),x.copy(u).multiplyScalar(p.x).addScaledVector(h,-f.x).multiplyScalar($),a[R].add(m),a[P].add(m),a[z].add(m),l[R].add(x),l[P].add(x),l[z].add(x))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)g(e.getX(j+0),e.getX(j+1),e.getX(j+2))}const b=new N,T=new N,S=new N,C=new N;function w(R){S.fromBufferAttribute(i,R),C.copy(S);const P=a[R];b.copy(P),b.sub(S.multiplyScalar(S.dot(P))).normalize(),T.crossVectors(C,P);const $=T.dot(l[R])<0?-1:1;r.setXYZW(R,b.x,b.y,b.z,$)}for(let R=0,P=_.length;R<P;++R){const z=_[R],$=z.start,q=z.count;for(let j=$,X=$+q;j<X;j+=3)w(e.getX(j+0)),w(e.getX(j+1)),w(e.getX(j+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let s=this.getAttribute("normal");if(s===void 0)s=new ls(new Float32Array(t.count*3),3),this.setAttribute("normal",s);else for(let d=0,p=s.count;d<p;d++)s.setXYZ(d,0,0,0);const i=new N,n=new N,r=new N,a=new N,l=new N,c=new N,h=new N,u=new N;if(e)for(let d=0,p=e.count;d<p;d+=3){const f=e.getX(d+0),m=e.getX(d+1),x=e.getX(d+2);i.fromBufferAttribute(t,f),n.fromBufferAttribute(t,m),r.fromBufferAttribute(t,x),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),a.fromBufferAttribute(s,f),l.fromBufferAttribute(s,m),c.fromBufferAttribute(s,x),a.add(h),l.add(h),c.add(h),s.setXYZ(f,a.x,a.y,a.z),s.setXYZ(m,l.x,l.y,l.z),s.setXYZ(x,c.x,c.y,c.z)}else for(let d=0,p=t.count;d<p;d+=3)i.fromBufferAttribute(t,d+0),n.fromBufferAttribute(t,d+1),r.fromBufferAttribute(t,d+2),h.subVectors(r,n),u.subVectors(i,n),h.cross(u),s.setXYZ(d+0,h.x,h.y,h.z),s.setXYZ(d+1,h.x,h.y,h.z),s.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)pt.fromBufferAttribute(e,t),pt.normalize(),e.setXYZ(t,pt.x,pt.y,pt.z)}toNonIndexed(){function e(a,l){const c=a.array,h=a.itemSize,u=a.normalized,d=new c.constructor(l.length*h);let p=0,f=0;for(let m=0,x=l.length;m<x;m++){a.isInterleavedBufferAttribute?p=l[m]*a.data.stride+a.offset:p=l[m]*h;for(let g=0;g<h;g++)d[f++]=c[p++]}return new ls(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ui,s=this.index.array,i=this.attributes;for(const a in i){const l=i[a],c=e(l,s);t.setAttribute(a,c)}const n=this.morphAttributes;for(const a in n){const l=[],c=n[a];for(let h=0,u=c.length;h<u;h++){const d=c[h],p=e(d,s);l.push(p)}t.morphAttributes[a]=l}t.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,l=r.length;a<l;a++){const c=r[a];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const 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){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const l in s){const c=s[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let n=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u];h.push(p.toJSON(e.data))}h.length>0&&(i[l]=h,n=!0)}n&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(e.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.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;const t={};this.name=e.name;const s=e.index;s!==null&&this.setIndex(s.clone());const i=e.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(t))}const n=e.morphAttributes;for(const c in n){const h=[],u=n[c];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const r=e.groups;for(let c=0,h=r.length;c<h;c++){const u=r[c];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Ws=new N,hc=new N,jo=new N,gi=new N,uc=new N,qo=new N,dc=new N;class mM{constructor(e=new N,t=new N(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,Ws)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ws.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ws.copy(this.origin).addScaledVector(this.direction,t),Ws.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){hc.copy(e).add(t).multiplyScalar(.5),jo.copy(t).sub(e).normalize(),gi.copy(this.origin).sub(hc);const n=e.distanceTo(t)*.5,r=-this.direction.dot(jo),a=gi.dot(this.direction),l=-gi.dot(jo),c=gi.lengthSq(),h=Math.abs(1-r*r);let u,d,p,f;if(h>0)if(u=r*l-a,d=r*a-l,f=n*h,u>=0)if(d>=-f)if(d<=f){const m=1/h;u*=m,d*=m,p=u*(u+r*d+2*a)+d*(r*u+d+2*l)+c}else d=n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;else d=-n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;else d<=-f?(u=Math.max(0,-(-r*n+a)),d=u>0?-n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c):d<=f?(u=0,d=Math.min(Math.max(-n,-l),n),p=d*(d+2*l)+c):(u=Math.max(0,-(r*n+a)),d=u>0?n:Math.min(Math.max(-n,-l),n),p=-u*u+d*(d+2*l)+c);else d=r>0?-n:n,u=Math.max(0,-(r*d+a)),p=-u*u+d*(d+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(hc).addScaledVector(jo,d),p}intersectSphere(e,t){Ws.subVectors(e.center,this.origin);const s=Ws.dot(this.direction),i=Ws.dot(Ws)-s*s,n=e.radius*e.radius;if(i>n)return null;const r=Math.sqrt(n-i),a=s-r,l=s+r;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return s===null?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,n,r,a,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(s=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(s=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),h>=0?(n=(e.min.y-d.y)*h,r=(e.max.y-d.y)*h):(n=(e.max.y-d.y)*h,r=(e.min.y-d.y)*h),s>r||n>i||((n>s||isNaN(s))&&(s=n),(r<i||isNaN(i))&&(i=r),u>=0?(a=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),s>l||a>i)||((a>s||s!==s)&&(s=a),(l<i||i!==i)&&(i=l),i<0)?null:this.at(s>=0?s:i,t)}intersectsBox(e){return this.intersectBox(e,Ws)!==null}intersectTriangle(e,t,s,i,n){uc.subVectors(t,e),qo.subVectors(s,e),dc.crossVectors(uc,qo);let r=this.direction.dot(dc),a;if(r>0){if(i)return null;a=1}else if(r<0)a=-1,r=-r;else return null;gi.subVectors(this.origin,e);const l=a*this.direction.dot(qo.crossVectors(gi,qo));if(l<0)return null;const c=a*this.direction.dot(uc.cross(gi));if(c<0||l+c>r)return null;const h=-a*gi.dot(dc);return h<0?null:this.at(h/r,n)}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)}}const ms=new N,$s=new N,pc=new N,js=new N,Fn=new N,Dn=new N,Mp=new N,fc=new N,mc=new N,gc=new N,yc=new ge,xc=new ge,_c=new ge;class Ss{constructor(e=new N,t=new N,s=new N){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),ms.subVectors(e,t),i.cross(ms);const n=i.lengthSq();return n>0?i.multiplyScalar(1/Math.sqrt(n)):i.set(0,0,0)}static getBarycoord(e,t,s,i,n){ms.subVectors(i,t),$s.subVectors(s,t),pc.subVectors(e,t);const r=ms.dot(ms),a=ms.dot($s),l=ms.dot(pc),c=$s.dot($s),h=$s.dot(pc),u=r*c-a*a;if(u===0)return n.set(0,0,0),null;const d=1/u,p=(c*l-a*h)*d,f=(r*h-a*l)*d;return n.set(1-p-f,f,p)}static containsPoint(e,t,s,i){return this.getBarycoord(e,t,s,i,js)===null?!1:js.x>=0&&js.y>=0&&js.x+js.y<=1}static getInterpolation(e,t,s,i,n,r,a,l){return this.getBarycoord(e,t,s,i,js)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(n,js.x),l.addScaledVector(r,js.y),l.addScaledVector(a,js.z),l)}static getInterpolatedAttribute(e,t,s,i,n,r){return yc.setScalar(0),xc.setScalar(0),_c.setScalar(0),yc.fromBufferAttribute(e,t),xc.fromBufferAttribute(e,s),_c.fromBufferAttribute(e,i),r.setScalar(0),r.addScaledVector(yc,n.x),r.addScaledVector(xc,n.y),r.addScaledVector(_c,n.z),r}static isFrontFacing(e,t,s,i){return ms.subVectors(s,t),$s.subVectors(e,t),ms.cross($s).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),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 ms.subVectors(this.c,this.b),$s.subVectors(this.a,this.b),ms.cross($s).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ss.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ss.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,n){return Ss.getInterpolation(e,this.a,this.b,this.c,t,s,i,n)}containsPoint(e){return Ss.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ss.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,n=this.c;let r,a;Fn.subVectors(i,s),Dn.subVectors(n,s),fc.subVectors(e,s);const l=Fn.dot(fc),c=Dn.dot(fc);if(l<=0&&c<=0)return t.copy(s);mc.subVectors(e,i);const h=Fn.dot(mc),u=Dn.dot(mc);if(h>=0&&u<=h)return t.copy(i);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return r=l/(l-h),t.copy(s).addScaledVector(Fn,r);gc.subVectors(e,n);const p=Fn.dot(gc),f=Dn.dot(gc);if(f>=0&&p<=f)return t.copy(n);const m=p*c-l*f;if(m<=0&&c>=0&&f<=0)return a=c/(c-f),t.copy(s).addScaledVector(Dn,a);const x=h*f-p*u;if(x<=0&&u-h>=0&&p-f>=0)return Mp.subVectors(n,i),a=(u-h)/(u-h+(p-f)),t.copy(i).addScaledVector(Mp,a);const g=1/(x+m+d);return r=m*g,a=d*g,t.copy(s).addScaledVector(Fn,r).addScaledVector(Dn,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ai extends Vt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ve(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 us,this.combine=pl,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}}const Cp=new Ie,Wi=new mM,Yo=new bl,Ep=new N,Xo=new N,Zo=new N,Ko=new N,bc=new N,Qo=new N,Ap=new N,Jo=new N;class li extends dt{constructor(e=new ui,t=new Ai){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(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let n=0,r=i.length;n<r;n++){const a=i[n].name||String(n);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=n}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,n=s.morphAttributes.position,r=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(n&&a){Qo.set(0,0,0);for(let l=0,c=n.length;l<c;l++){const h=a[l],u=n[l];h!==0&&(bc.fromBufferAttribute(u,e),r?Qo.addScaledVector(bc,h):Qo.addScaledVector(bc.sub(t),h))}t.add(Qo)}return t}raycast(e,t){const s=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(s.boundingSphere===null&&s.computeBoundingSphere(),Yo.copy(s.boundingSphere),Yo.applyMatrix4(n),Wi.copy(e.ray).recast(e.near),!(Yo.containsPoint(Wi.origin)===!1&&(Wi.intersectSphere(Yo,Ep)===null||Wi.origin.distanceToSquared(Ep)>(e.far-e.near)**2))&&(Cp.copy(n).invert(),Wi.copy(e.ray).applyMatrix4(Cp),!(s.boundingBox!==null&&Wi.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Wi)))}_computeIntersections(e,t,s){let i;const n=this.geometry,r=this.material,a=n.index,l=n.attributes.position,c=n.attributes.uv,h=n.attributes.uv1,u=n.attributes.normal,d=n.groups,p=n.drawRange;if(a!==null)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const x=d[f],g=r[x.materialIndex],_=Math.max(x.start,p.start),b=Math.min(a.count,Math.min(x.start+x.count,p.start+p.count));for(let T=_,S=b;T<S;T+=3){const C=a.getX(T),w=a.getX(T+1),R=a.getX(T+2);i=ea(this,g,e,s,c,h,u,C,w,R),i&&(i.faceIndex=Math.floor(T/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(a.count,p.start+p.count);for(let x=f,g=m;x<g;x+=3){const _=a.getX(x),b=a.getX(x+1),T=a.getX(x+2);i=ea(this,r,e,s,c,h,u,_,b,T),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(r))for(let f=0,m=d.length;f<m;f++){const x=d[f],g=r[x.materialIndex],_=Math.max(x.start,p.start),b=Math.min(l.count,Math.min(x.start+x.count,p.start+p.count));for(let T=_,S=b;T<S;T+=3){const C=T,w=T+1,R=T+2;i=ea(this,g,e,s,c,h,u,C,w,R),i&&(i.faceIndex=Math.floor(T/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{const f=Math.max(0,p.start),m=Math.min(l.count,p.start+p.count);for(let x=f,g=m;x<g;x+=3){const _=x,b=x+1,T=x+2;i=ea(this,r,e,s,c,h,u,_,b,T),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}}}function gM(o,e,t,s,i,n,r,a){let l;if(e.side===Gt?l=s.intersectTriangle(r,n,i,!0,a):l=s.intersectTriangle(i,n,r,e.side===Qs,a),l===null)return null;Jo.copy(a),Jo.applyMatrix4(o.matrixWorld);const c=t.ray.origin.distanceTo(Jo);return c<t.near||c>t.far?null:{distance:c,point:Jo.clone(),object:o}}function ea(o,e,t,s,i,n,r,a,l,c){o.getVertexPosition(a,Xo),o.getVertexPosition(l,Zo),o.getVertexPosition(c,Ko);const h=gM(o,e,t,s,Xo,Zo,Ko,Ap);if(h){const u=new N;Ss.getBarycoord(Ap,Xo,Zo,Ko,u),i&&(h.uv=Ss.getInterpolatedAttribute(i,a,l,c,u,new he)),n&&(h.uv1=Ss.getInterpolatedAttribute(n,a,l,c,u,new he)),r&&(h.normal=Ss.getInterpolatedAttribute(r,a,l,c,u,new N),h.normal.dot(s.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:l,c,normal:new N,materialIndex:0};Ss.getNormal(Xo,Zo,Ko,d.normal),h.face=d,h.barycoord=u}return h}class ku extends du{constructor(e=-1,t=1,s=1,i=-1,n=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=n,this.far=r,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,n,r){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let n=s-e,r=s+e,a=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=c*this.view.offsetX,r=n+c*this.view.width,a-=h*this.view.offsetY,l=a-h*this.view.height}this.projectionMatrix.makeOrthographic(n,r,a,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const Tc=new ku(-1,1,1,-1,0,1);class yM extends ui{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Pt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Pt(t,2))}}const xM=new yM;class zu extends li{constructor(e=null){super(xM,e),this.camera=Tc,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Tc)}render(e){e.render(this,Tc)}}const El=1/6,ry=o=>fe(El,fe(o,fe(o,o.negate().add(3)).sub(3)).add(1)),Vh=o=>fe(El,fe(o,fe(o,fe(3,o).sub(6))).add(4)),oy=o=>fe(El,fe(o,fe(o,fe(-3,o).add(3)).add(3)).add(1)),Hh=o=>fe(El,_l(o,3)),Rp=o=>ry(o).add(Vh(o)),Np=o=>oy(o).add(Hh(o)),Pp=o=>Dt(-1,Vh(o).div(ry(o).add(Vh(o)))),Fp=o=>Dt(1,Hh(o).div(oy(o).add(Hh(o)))),Dp=(o,e,t)=>{const s=o.uvNode,i=fe(s,e.zw).add(.5),n=un(i),r=Ui(i),a=Rp(r.x),l=Np(r.x),c=Pp(r.x),h=Fp(r.x),u=Pp(r.y),d=Fp(r.y),p=H(n.x.add(c),n.y.add(u)).sub(.5).mul(e.xy),f=H(n.x.add(h),n.y.add(u)).sub(.5).mul(e.xy),m=H(n.x.add(c),n.y.add(d)).sub(.5).mul(e.xy),x=H(n.x.add(h),n.y.add(d)).sub(.5).mul(e.xy),g=Rp(r.y).mul(Dt(a.mul(o.sample(p).level(t)),l.mul(o.sample(f).level(t)))),_=Np(r.y).mul(Dt(a.mul(o.sample(m).level(t)),l.mul(o.sample(x).level(t))));return g.add(_)},_M=L(([o,e=B(3)])=>{const t=H(o.size(ke(e))),s=H(o.size(ke(e.add(1)))),i=Us(1,t),n=Us(1,s),r=Dp(o,ne(i,t),un(e)),a=Dp(o,ne(n,s),Mu(e));return Ui(e).mix(r,a)}),Lr=new us,Sc=new Ie;class zt extends re{static get type(){return"SceneNode"}constructor(e=zt.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=this.scene!==null?this.scene:e.scene;let i;return t===zt.BACKGROUND_BLURRINESS?i=Be("backgroundBlurriness","float",s):t===zt.BACKGROUND_INTENSITY?i=Be("backgroundIntensity","float",s):t===zt.BACKGROUND_ROTATION?i=Q("mat4").label("backgroundRotation").setGroup(K).onRenderUpdate(()=>{const n=s.background;return n!==null&&n.isTexture&&n.mapping!==tu?(Lr.copy(s.backgroundRotation),Lr.x*=-1,Lr.y*=-1,Lr.z*=-1,Sc.makeRotationFromEuler(Lr)):Sc.identity(),Sc}):console.error("THREE.SceneNode: Unknown scope:",t),i}}zt.BACKGROUND_BLURRINESS="backgroundBlurriness";zt.BACKGROUND_INTENSITY="backgroundIntensity";zt.BACKGROUND_ROTATION="backgroundRotation";const bM=V(zt,zt.BACKGROUND_BLURRINESS),Op=V(zt,zt.BACKGROUND_INTENSITY),TM=V(zt,zt.BACKGROUND_ROTATION),SM=L(({texture:o,uv:e})=>{const s=I().toVar();return Ze(e.x.lessThan(1e-4),()=>{s.assign(I(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{s.assign(I(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{s.assign(I(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{s.assign(I(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{s.assign(I(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{s.assign(I(0,0,-1))}).Else(()=>{const n=o.sample(e.add(I(-.01,0,0))).r.sub(o.sample(e.add(I(.01,0,0))).r),r=o.sample(e.add(I(0,-.01,0))).r.sub(o.sample(e.add(I(0,.01,0))).r),a=o.sample(e.add(I(0,0,-.01))).r.sub(o.sample(e.add(I(0,0,.01))).r);s.assign(I(n,r,a))}),s.normalize()});class vM extends br{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return I(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.isRenderTargetTexture===!0||s.isFramebufferTexture===!0)&&(this.sampler?t=t.flipY():t=t.setY(ke(ar(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return SM({texture:this,uv:e})}}const wM=U(vM).setParameterLength(1,3),ta=new he;class MM extends br{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Bp extends MM{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class Al extends nt{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const n=new Is;n.isRenderTargetTexture=!0,n.name="depth";const r=new fn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:rs,...i});r.texture.name="output",r.depthTexture=n,this.renderTarget=r,this._textures={output:r.texture,depth:n},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Q(0),this._cameraFar=Q(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=ue.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];return t===void 0&&(t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)),t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(t!==void 0){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return t===void 0&&(t=k(new Bp(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=k(new Bp(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=Xg(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const s=this._cameraNear,i=this._cameraFar,n=this.getViewZNode(e);this._linearDepthNodes[e]=t=fo(n,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=this.options.samples===void 0?e.samples:this.options.samples,e.backend.isWebGLBackend===!0&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Al.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,n;const r=t.getOutputRenderTarget();r&&r.isXRRenderTarget===!0?(n=1,i=t.xr.getCamera(),t.xr.updateCamera(i),ta.set(r.width,r.height)):(i=this.camera,n=t.getPixelRatio(),t.getSize(ta)),this._pixelRatio=n,this.setSize(ta.width,ta.height);const a=t.getRenderTarget(),l=t.getMRT(),c=i.layers.mask;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(const h in this._previousTextures)this.toggleTexture(h);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(a),t.setMRT(l),i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Al.COLOR="color";Al.DEPTH="depth";const CM=L(([o,e])=>o.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),EM=L(([o,e])=>(o=o.mul(e),o.div(o.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),AM=L(([o,e])=>{o=o.mul(e),o=o.sub(.004).max(0);const t=o.mul(o.mul(6.2).add(.5)),s=o.mul(o.mul(6.2).add(1.7)).add(.06);return t.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),RM=L(([o])=>{const e=o.mul(o.add(.0245786)).sub(90537e-9),t=o.mul(o.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),NM=L(([o,e])=>{const t=Ft(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=Ft(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return o=o.mul(e).div(.6),o=t.mul(o),o=RM(o),o=s.mul(o),o.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),PM=Ft(I(1.6605,-.1246,-.0182),I(-.5876,1.1329,-.1006),I(-.0728,-.0083,1.1187)),FM=Ft(I(.6274,.0691,.0164),I(.3293,.9195,.088),I(.0433,.0113,.8956)),DM=L(([o])=>{const e=I(o).toVar(),t=I(e.mul(e)).toVar(),s=I(t.mul(t)).toVar();return B(15.5).mul(s.mul(t)).sub(fe(40.14,s.mul(e))).add(fe(31.96,s).sub(fe(6.868,t.mul(e))).add(fe(.4298,t).add(fe(.1191,e).sub(.00232))))}),OM=L(([o,e])=>{const t=I(o).toVar(),s=Ft(I(.856627153315983,.137318972929847,.11189821299995),I(.0951212405381588,.761241990602591,.0767994186031903),I(.0482516061458583,.101439036467562,.811302368396859)),i=Ft(I(1.1271005818144368,-.1413297634984383,-.14132976349843826),I(-.11060664309660323,1.157823702216272,-.11060664309660294),I(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=B(-12.47393),r=B(4.026069);return t.mulAssign(e),t.assign(FM.mul(t)),t.assign(s.mul(t)),t.assign(vt(t,1e-10)),t.assign(ii(t)),t.assign(t.sub(n).div(r.sub(n))),t.assign(ai(t,0,1)),t.assign(DM(t)),t.assign(i.mul(t)),t.assign(_l(vt(I(0),t),I(2.2))),t.assign(PM.mul(t)),t.assign(ai(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),BM=L(([o,e])=>{const t=B(.76),s=B(.15);o=o.mul(e);const i=fr(o.r,fr(o.g,o.b)),n=Tt(i.lessThan(.08),i.sub(fe(6.25,i.mul(i))),.04);o.subAssign(n);const r=vt(o.r,vt(o.g,o.b));Ze(r.lessThan(t),()=>o);const a=At(1,t),l=At(1,a.mul(a).div(r.add(a.sub(t))));o.mulAssign(l.div(r));const c=At(1,Us(1,s.mul(r.sub(l)).add(1)));return Ge(o,I(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class ct extends re{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const i of t)i.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class IM extends ct{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return s===void 0&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,n=s.type,r=e.getCodeFromNode(this,n);i!==""&&(r.name=i);const a=e.getPropertyName(r),l=this.getNodeFunction(e).getCode(a);return r.code=l+`
|
|
74
|
+
`,t==="property"?a:e.format(`${a}()`,n,t)}}function ay(o){let e;const t=o.context.getViewZ;return t!==void 0&&(e=t(this)),(e||st.z).negate()}const LM=L(([o,e],t)=>{const s=ay(t);return Bi(o,e,s)}),UM=L(([o],e)=>{const t=ay(e);return o.mul(o,t,t).negate().exp().oneMinus()}),Ip=L(([o,e])=>ne(e.toFloat().mix(uo.rgb,o.toVec3()),uo.a));class kM extends re{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;s.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier
|
|
75
|
+
`):e.addLineFlowCode(`${t}Barrier()`,this)}}U(kM);class Gs extends re{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,n=this.getNodeType(e),r=this.getInputType(e),a=this.pointerNode,l=this.valueNode,c=[];c.push(`&${a.build(e,r)}`),l!==null&&c.push(l.build(e,r));const h=`${e.getMethod(i,n)}( ${c.join(", ")} )`;if(s.length===1&&s[0].isStackNode===!0)e.addLineFlowCode(h,this);else return t.constNode===void 0&&(t.constNode=mr(h,n).toConst()),t.constNode.build(e)}}Gs.ATOMIC_LOAD="atomicLoad";Gs.ATOMIC_STORE="atomicStore";Gs.ATOMIC_ADD="atomicAdd";Gs.ATOMIC_SUB="atomicSub";Gs.ATOMIC_MAX="atomicMax";Gs.ATOMIC_MIN="atomicMin";Gs.ATOMIC_AND="atomicAnd";Gs.ATOMIC_OR="atomicOr";Gs.ATOMIC_XOR="atomicXor";U(Gs);let sa;function Rl(o){sa=sa||new WeakMap;let e=sa.get(o);return e===void 0&&sa.set(o,e={}),e}function ly(o){const e=Rl(o);return e.shadowMatrix||(e.shadowMatrix=Q("mat4").setGroup(K).onRenderUpdate(t=>((o.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&o.shadow.updateMatrices(o),o.shadow.matrix)))}function zM(o,e=vo){const t=ly(o).mul(e);return t.xyz.div(t.w)}function cy(o){const e=Rl(o);return e.position||(e.position=Q(new N).setGroup(K).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(o.matrixWorld)))}function GM(o){const e=Rl(o);return e.targetPosition||(e.targetPosition=Q(new N).setGroup(K).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(o.target.matrixWorld)))}function hy(o){const e=Rl(o);return e.viewPosition||(e.viewPosition=Q(new N).setGroup(K).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new N,s.value.setFromMatrixPosition(o.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const uy=o=>hi.transformDirection(cy(o).sub(GM(o))),VM=o=>o.sort((e,t)=>e.id-t.id),HM=(o,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===o)return t;return null},vc=new WeakMap,Ur=[];class dy extends re{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=I().toVar(),this.totalSpecularNode=I().toVar(),this.outgoingLightNode=I().toVar(),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let s=0;s<e.length;s++){const i=e[s];if(Ur.push(i.id),Ur.push(i.castShadow?1:0),i.isSpotLight===!0){const n=i.map!==null?i.map.id:-1,r=i.colorNode?i.colorNode.getCacheKey():-1;Ur.push(n,r)}}const t=hu(Ur);return Ur.length=0,t}getHash(e){if(this._lightNodesHash===null){this._lightNodes===null&&this.setupLightsNode(e);const t=[];for(const s of this._lightNodes)t.push(s.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=VM(this._lights),n=e.renderer.library;for(const r of i)if(r.isNode)t.push(k(r));else{let a=null;if(s!==null&&(a=HM(r.id,s)),a===null){const l=n.getLightNodeClass(r.constructor);if(l===null){console.warn(`LightsNode.setupNodeLights: Light node not found for ${r.constructor.name}`);continue}let c=null;vc.has(r)?c=vc.get(r):(c=k(new l(r)),vc.set(r,c)),t.push(c)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.direct({...s,lightNode:t,reflectedLight:n},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:n}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:n},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return this._lightNodes===null&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,n=i.lightingModel,r=e.getNodeProperties(this);if(n){const{totalDiffuseNode:a,totalSpecularNode:l}=this;i.outgoingLight=s;const c=e.addStack();r.nodes=c.nodes,n.start(e);const{backdrop:h,backdropAlpha:u}=i,{directDiffuse:d,directSpecular:p,indirectDiffuse:f,indirectSpecular:m}=i.reflectedLight;let x=d.add(f);h!==null&&(u!==null?x=I(u.mix(x,h)):x=I(h),i.material.transparent=!0),a.assign(x),l.assign(p.add(m)),s.assign(a.add(l)),n.finish(e),s=s.bypass(e.removeStack())}else r.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class WM extends re{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ue.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){py.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||vo)}}const py=dg("vec3","shadowPositionWorld");function $M(o,e={}){return e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure,e.outputColorSpace=o.outputColorSpace,e.renderTarget=o.getRenderTarget(),e.activeCubeFace=o.getActiveCubeFace(),e.activeMipmapLevel=o.getActiveMipmapLevel(),e.renderObjectFunction=o.getRenderObjectFunction(),e.pixelRatio=o.getPixelRatio(),e.mrt=o.getMRT(),e.clearColor=o.getClearColor(e.clearColor||new ve),e.clearAlpha=o.getClearAlpha(),e.autoClear=o.autoClear,e.scissorTest=o.getScissorTest(),e}function jM(o,e){return e=$M(o,e),o.setMRT(null),o.setRenderObjectFunction(null),o.setClearColor(0,1),o.autoClear=!0,e}function qM(o,e){o.toneMapping=e.toneMapping,o.toneMappingExposure=e.toneMappingExposure,o.outputColorSpace=e.outputColorSpace,o.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),o.setRenderObjectFunction(e.renderObjectFunction),o.setPixelRatio(e.pixelRatio),o.setMRT(e.mrt),o.setClearColor(e.clearColor,e.clearAlpha),o.autoClear=e.autoClear,o.setScissorTest(e.scissorTest)}function YM(o,e={}){return e.background=o.background,e.backgroundNode=o.backgroundNode,e.overrideMaterial=o.overrideMaterial,e}function XM(o,e){return e=YM(o,e),o.background=null,o.backgroundNode=null,o.overrideMaterial=null,e}function ZM(o,e){o.background=e.background,o.backgroundNode=e.backgroundNode,o.overrideMaterial=e.overrideMaterial}function KM(o,e,t){return t=jM(o,t),t=XM(e,t),t}function QM(o,e,t){qM(o,t),ZM(e,t)}const Lp=new WeakMap,JM=L(({depthTexture:o,shadowCoord:e,depthLayer:t})=>{let s=_e(o,e.xy).label("t_basic");return o.isArrayTexture&&(s=s.depth(t)),s.compare(e.z)}),eC=L(({depthTexture:o,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(x,g)=>{let _=_e(o,x);return o.isArrayTexture&&(_=_.depth(s)),_.compare(g)},n=Be("mapSize","vec2",t).setGroup(K),r=Be("radius","float",t).setGroup(K),a=H(1).div(n),l=a.x.negate().mul(r),c=a.y.negate().mul(r),h=a.x.mul(r),u=a.y.mul(r),d=l.div(2),p=c.div(2),f=h.div(2),m=u.div(2);return Dt(i(e.xy.add(H(l,c)),e.z),i(e.xy.add(H(0,c)),e.z),i(e.xy.add(H(h,c)),e.z),i(e.xy.add(H(d,p)),e.z),i(e.xy.add(H(0,p)),e.z),i(e.xy.add(H(f,p)),e.z),i(e.xy.add(H(l,0)),e.z),i(e.xy.add(H(d,0)),e.z),i(e.xy,e.z),i(e.xy.add(H(f,0)),e.z),i(e.xy.add(H(h,0)),e.z),i(e.xy.add(H(d,m)),e.z),i(e.xy.add(H(0,m)),e.z),i(e.xy.add(H(f,m)),e.z),i(e.xy.add(H(l,u)),e.z),i(e.xy.add(H(0,u)),e.z),i(e.xy.add(H(h,u)),e.z)).mul(1/17)}),tC=L(({depthTexture:o,shadowCoord:e,shadow:t,depthLayer:s})=>{const i=(u,d)=>{let p=_e(o,u);return o.isArrayTexture&&(p=p.depth(s)),p.compare(d)},n=Be("mapSize","vec2",t).setGroup(K),r=H(1).div(n),a=r.x,l=r.y,c=e.xy,h=Ui(c.mul(n).add(.5));return c.subAssign(h.mul(r)),Dt(i(c,e.z),i(c.add(H(a,0)),e.z),i(c.add(H(0,l)),e.z),i(c.add(r),e.z),Ge(i(c.add(H(a.negate(),0)),e.z),i(c.add(H(a.mul(2),0)),e.z),h.x),Ge(i(c.add(H(a.negate(),l)),e.z),i(c.add(H(a.mul(2),l)),e.z),h.x),Ge(i(c.add(H(0,l.negate())),e.z),i(c.add(H(0,l.mul(2))),e.z),h.y),Ge(i(c.add(H(a,l.negate())),e.z),i(c.add(H(a,l.mul(2))),e.z),h.y),Ge(Ge(i(c.add(H(a.negate(),l.negate())),e.z),i(c.add(H(a.mul(2),l.negate())),e.z),h.x),Ge(i(c.add(H(a.negate(),l.mul(2))),e.z),i(c.add(H(a.mul(2),l.mul(2))),e.z),h.x),h.y)).mul(1/9)}),sC=L(({depthTexture:o,shadowCoord:e,depthLayer:t})=>{const s=B(1).toVar();let i=_e(o).sample(e.xy);o.isArrayTexture&&(i=i.depth(t)),i=i.rg;const n=Cg(e.z,i.x);return Ze(n.notEqual(B(1)),()=>{const r=e.z.sub(i.x),a=vt(0,i.y.mul(i.y));let l=a.div(a.add(r.mul(r)));l=ai(At(l,.3).div(.95-.3)),s.assign(ai(vt(n,l)))}),s}),iC=L(([o,e,t])=>{let s=vo.sub(o).length();return s=s.sub(e).div(t.sub(e)),s=s.saturate(),s}),nC=o=>{const e=o.shadow.camera,t=Be("near","float",e).setGroup(K),s=Be("far","float",e).setGroup(K),i=yv(o);return iC(i,t,s)},rC=o=>{let e=Lp.get(o);if(e===void 0){const t=o.isPointLight?nC(o):null;e=new it,e.colorNode=ne(0,0,0,1),e.depthNode=t,e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.fog=!1,Lp.set(o,e)}return e},Up=new vs,On=[],oC=(o,e,t,s)=>{On[0]=o,On[1]=e;let i=Up.get(On);return(i===void 0||i.shadowType!==t||i.useVelocity!==s)&&(i=(n,r,a,l,c,h,...u)=>{(n.castShadow===!0||n.receiveShadow&&t===Na)&&(s&&(Km(n).useVelocity=!0),n.onBeforeShadow(o,n,a,e.camera,l,r.overrideMaterial,h),o.renderObject(n,r,a,l,c,h,...u),n.onAfterShadow(o,n,a,e.camera,l,r.overrideMaterial,h))},i.shadowType=t,i.useVelocity=s,Up.set(On,i)),On[0]=null,On[1]=null,i},aC=L(({samples:o,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanVertical"),r=B(0).toVar("squareMeanVertical"),a=o.lessThanEqual(B(1)).select(B(0),B(2).div(o.sub(1))),l=o.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:ke(0),end:ke(o),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(a));let d=s.sample(Dt(Ml.xy,H(0,u).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),r.addAssign(d.mul(d))}),n.divAssign(o),r.divAssign(o);const c=wu(r.sub(n.mul(n)));return H(n,c)}),lC=L(({samples:o,radius:e,size:t,shadowPass:s,depthLayer:i})=>{const n=B(0).toVar("meanHorizontal"),r=B(0).toVar("squareMeanHorizontal"),a=o.lessThanEqual(B(1)).select(B(0),B(2).div(o.sub(1))),l=o.lessThanEqual(B(1)).select(B(0),B(-1));Ts({start:ke(0),end:ke(o),type:"int",condition:"<"},({i:h})=>{const u=l.add(B(h).mul(a));let d=s.sample(Dt(Ml.xy,H(u,0).mul(e)).div(t));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),r.addAssign(Dt(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(o),r.divAssign(o);const c=wu(r.sub(n.mul(n)));return H(n,c)}),cC=[JM,eC,tC,sC];let wc;const ia=new zu;class fy extends WM{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:n,depthLayer:r}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),l=t({depthTexture:s,shadowCoord:i,shadow:n,depthLayer:r});return a.select(l,B(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,n=Be("bias","float",s).setGroup(K);let r=t,a;if(s.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)r=r.xyz.div(r.w),a=r.z,i.coordinateSystem===Oi&&(a=a.mul(2).sub(1));else{const l=r.w;r=r.xy.div(l);const c=Be("near","float",s.camera).setGroup(K),h=Be("far","float",s.camera).setGroup(K);a=Zg(l.negate(),c,h)}return r=I(r.x,r.y.oneMinus(),a.add(n)),r}getShadowFilterFn(e){return cC[e]}setupRenderTarget(e,t){const s=new Is(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=cu;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t}=e,{light:s,shadow:i}=this,n=t.shadowMap.type,{depthTexture:r,shadowMap:a}=this.setupRenderTarget(i,e);if(i.camera.updateProjectionMatrix(),n===Na&&i.isPointLightShadow!==!0){r.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:cn,type:rs,depthBuffer:!1}));let g=_e(r);r.isArrayTexture&&(g=g.depth(this.depthLayer));let _=_e(this.vsmShadowMapVertical.texture);r.isArrayTexture&&(_=_.depth(this.depthLayer));const b=Be("blurSamples","float",i).setGroup(K),T=Be("radius","float",i).setGroup(K),S=Be("mapSize","vec2",i).setGroup(K);let C=this.vsmMaterialVertical||(this.vsmMaterialVertical=new it);C.fragmentNode=aC({samples:b,radius:T,size:S,shadowPass:g,depthLayer:this.depthLayer}).context(e.getSharedContext()),C.name="VSMVertical",C=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new it),C.fragmentNode=lC({samples:b,radius:T,size:S,shadowPass:_,depthLayer:this.depthLayer}).context(e.getSharedContext()),C.name="VSMHorizontal"}const l=Be("intensity","float",i).setGroup(K),c=Be("normalBias","float",i).setGroup(K),h=ly(s).mul(py.add(Iu.mul(c))),u=this.setupShadowCoord(e,h),d=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(d===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=n===Na&&i.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:r,f=this.setupShadowFilter(e,{filterFn:d,shadowTexture:a.texture,depthTexture:p,shadowCoord:u,shadow:i,depthLayer:this.depthLayer});let m=_e(a.texture,u);r.isArrayTexture&&(m=m.depth(this.depthLayer));const x=Ge(1,f.rgb.mix(m,1),l.mul(m.a)).toVar();return this.shadowMap=a,this.shadow.map=a,x}setup(e){if(e.renderer.shadowMap.enabled!==!1)return L(()=>{let t=this._node;return this.setupShadowPosition(e),t===null&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth),n.render(r,t.camera)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:n,scene:r,camera:a}=e,l=n.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;const h=i.camera.layers.mask;(i.camera.layers.mask&4294967294)===0&&(i.camera.layers.mask=a.layers.mask);const u=n.getRenderObjectFunction(),d=n.getMRT(),p=d?d.has("velocity"):!1;wc=KM(n,r,wc),r.overrideMaterial=rC(s),n.setRenderObjectFunction(oC(n,i,l,p)),n.setClearColor(0,0),n.setRenderTarget(t),this.renderShadow(e),n.setRenderObjectFunction(u),l===Na&&i.isPointLightShadow!==!0&&this.vsmPass(n),i.camera.layers.mask=h,QM(n,r,wc)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),ia.material=this.vsmMaterialVertical,ia.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),ia.material=this.vsmMaterialHorizontal,ia.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const hC=(o,e)=>k(new fy(o,e)),uC=new ve,Ps=L(([o,e])=>{const t=o.toVar(),s=ns(t),i=Us(1,vt(s.x,vt(s.y,s.z)));s.mulAssign(i),t.mulAssign(i.mul(e.mul(2).oneMinus()));const n=H(t.xy).toVar(),a=e.mul(1.5).oneMinus();return Ze(s.z.greaterThanEqual(a),()=>{Ze(t.z.greaterThan(0),()=>{n.x.assign(At(4,t.x))})}).ElseIf(s.x.greaterThanEqual(a),()=>{const l=ll(t.x);n.x.assign(t.z.mul(l).add(l.mul(2)))}).ElseIf(s.y.greaterThanEqual(a),()=>{const l=ll(t.y);n.x.assign(t.x.add(l.mul(2)).add(2)),n.y.assign(t.z.mul(l).sub(2))}),H(.125,.25).mul(n).add(H(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),dC=L(({depthTexture:o,bd3D:e,dp:t,texelSize:s})=>_e(o,Ps(e,s.y)).compare(t)),pC=L(({depthTexture:o,bd3D:e,dp:t,texelSize:s,shadow:i})=>{const n=Be("radius","float",i).setGroup(K),r=H(-1,1).mul(n).mul(s.y);return _e(o,Ps(e.add(r.xyy),s.y)).compare(t).add(_e(o,Ps(e.add(r.yyy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.xyx),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yyx),s.y)).compare(t)).add(_e(o,Ps(e,s.y)).compare(t)).add(_e(o,Ps(e.add(r.xxy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yxy),s.y)).compare(t)).add(_e(o,Ps(e.add(r.xxx),s.y)).compare(t)).add(_e(o,Ps(e.add(r.yxx),s.y)).compare(t)).mul(1/9)}),fC=L(({filterFn:o,depthTexture:e,shadowCoord:t,shadow:s})=>{const i=t.xyz.toVar(),n=i.length(),r=Q("float").setGroup(K).onRenderUpdate(()=>s.camera.near),a=Q("float").setGroup(K).onRenderUpdate(()=>s.camera.far),l=Be("bias","float",s).setGroup(K),c=Q(s.mapSize).setGroup(K),h=B(1).toVar();return Ze(n.sub(a).lessThanEqual(0).and(n.sub(r).greaterThanEqual(0)),()=>{const u=n.sub(r).div(a.sub(r)).toVar();u.addAssign(l);const d=i.normalize(),p=H(1).div(c.mul(H(4,2)));h.assign(o({depthTexture:e,bd3D:d,dp:u,texelSize:p,shadow:s}))}),h}),kp=new ge,Bn=new he,kr=new he;class mC extends fy{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===C_?dC:pC}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r}){return fC({filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:n,shadow:r})}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:n,scene:r}=e,a=t.getFrameExtents();kr.copy(t.mapSize),kr.multiply(a),s.setSize(kr.width,kr.height),Bn.copy(t.mapSize);const l=n.autoClear,c=n.getClearColor(uC),h=n.getClearAlpha();n.autoClear=!1,n.setClearColor(t.clearColor,t.clearAlpha),n.clear();const u=t.getViewportCount();for(let d=0;d<u;d++){const p=t.getViewport(d),f=Bn.x*p.x,m=kr.y-Bn.y-Bn.y*p.y;kp.set(f,m,Bn.x*p.z,Bn.y*p.w),s.viewport.copy(kp),t.updateMatrices(i,d),n.render(r,t.camera)}n.autoClear=l,n.setClearColor(c,h)}}const gC=(o,e)=>k(new mC(o,e));class mn extends Tr{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new ve,this.colorNode=e&&e.colorNode||Q(this.color).setGroup(K),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ue.FRAME}getHash(){return this.light.uuid}getLightVector(e){return hy(this.light).sub(e.context.positionView||st)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return hC(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let s=this.shadowColorNode;if(s===null){const i=this.light.shadow.shadowNode;let n;i!==void 0?n=k(i):n=this.setupShadowNode(),this.shadowNode=n,this.shadowColorNode=s=this.colorNode.mul(n),this.baseColorNode=this.colorNode}this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const my=L(({lightDistance:o,cutoffDistance:e,decayExponent:t})=>{const s=o.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(s.mul(o.div(e).pow4().oneMinus().clamp().pow2()),s)}),yC=({color:o,lightVector:e,cutoffDistance:t,decayExponent:s})=>{const i=e.normalize(),n=e.length(),r=my({lightDistance:n,cutoffDistance:t,decayExponent:s}),a=o.mul(r);return{lightDirection:i,lightColor:a}};class xC extends mn{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Q(0).setGroup(K),this.decayExponentNode=Q(2).setGroup(K)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return gC(this.light)}setupDirect(e){return yC({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const zp=B(1),Wh=B(-2),na=B(.8),Mc=B(-1),ra=B(.4),Cc=B(2),oa=B(.305),Ec=B(3),Gp=B(.21),_C=B(4),Vp=B(4),bC=B(16),TC=L(([o])=>{const e=I(ns(o)).toVar(),t=B(-1).toVar();return Ze(e.x.greaterThan(e.z),()=>{Ze(e.x.greaterThan(e.y),()=>{t.assign(Tt(o.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Tt(o.y.greaterThan(0),1,4))})}).Else(()=>{Ze(e.z.greaterThan(e.y),()=>{t.assign(Tt(o.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Tt(o.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),SC=L(([o,e])=>{const t=H().toVar();return Ze(e.equal(0),()=>{t.assign(H(o.z,o.y).div(ns(o.x)))}).ElseIf(e.equal(1),()=>{t.assign(H(o.x.negate(),o.z.negate()).div(ns(o.y)))}).ElseIf(e.equal(2),()=>{t.assign(H(o.x.negate(),o.y).div(ns(o.z)))}).ElseIf(e.equal(3),()=>{t.assign(H(o.z.negate(),o.y).div(ns(o.x)))}).ElseIf(e.equal(4),()=>{t.assign(H(o.x.negate(),o.z).div(ns(o.y)))}).Else(()=>{t.assign(H(o.x,o.y).div(ns(o.z)))}),fe(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),vC=L(([o])=>{const e=B(0).toVar();return Ze(o.greaterThanEqual(na),()=>{e.assign(zp.sub(o).mul(Mc.sub(Wh)).div(zp.sub(na)).add(Wh))}).ElseIf(o.greaterThanEqual(ra),()=>{e.assign(na.sub(o).mul(Cc.sub(Mc)).div(na.sub(ra)).add(Mc))}).ElseIf(o.greaterThanEqual(oa),()=>{e.assign(ra.sub(o).mul(Ec.sub(Cc)).div(ra.sub(oa)).add(Cc))}).ElseIf(o.greaterThanEqual(Gp),()=>{e.assign(oa.sub(o).mul(_C.sub(Ec)).div(oa.sub(Gp)).add(Ec))}).Else(()=>{e.assign(B(-2).mul(ii(fe(1.16,o))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),wC=L(([o,e])=>{const t=o.toVar();t.assign(fe(2,t).sub(1));const s=I(t,1).toVar();return Ze(e.equal(0),()=>{s.assign(s.zyx)}).ElseIf(e.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),MC=L(([o,e,t,s,i,n])=>{const r=B(t),a=I(e),l=ai(vC(r),Wh,n),c=Ui(l),h=un(l),u=I($h(o,a,h,s,i,n)).toVar();return Ze(c.notEqual(0),()=>{const d=I($h(o,a,h.add(1),s,i,n)).toVar();u.assign(Ge(u,d,c))}),u}),$h=L(([o,e,t,s,i,n])=>{const r=B(t).toVar(),a=I(e),l=B(TC(a)).toVar(),c=B(vt(Vp.sub(r),0)).toVar();r.assign(vt(r,Vp));const h=B(To(r)).toVar(),u=H(SC(a,l).mul(h.sub(2)).add(1)).toVar();return Ze(l.greaterThan(2),()=>{u.y.addAssign(h),l.subAssign(3)}),u.x.addAssign(l.mul(h)),u.x.addAssign(c.mul(fe(3,bC))),u.y.addAssign(fe(4,To(n).sub(h))),u.x.mulAssign(s),u.y.mulAssign(i),o.sample(u).grad(H(),H())}),Ac=L(({envMap:o,mipInt:e,outputDirection:t,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:r,CUBEUV_MAX_MIP:a})=>{const l=wi(s),c=t.mul(l).add(i.cross(t).mul(_s(s))).add(i.mul(i.dot(t).mul(l.oneMinus())));return $h(o,c,e,n,r,a)}),CC=L(({n:o,latitudinal:e,poleAxis:t,outputDirection:s,weights:i,samples:n,dTheta:r,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})=>{const d=I(Tt(e,t,Eg(t,s))).toVar();Ze(d.equal(I(0)),()=>{d.assign(I(s.z,0,s.x.negate()))}),d.assign(So(d));const p=I().toVar();return p.addAssign(i.element(0).mul(Ac({theta:0,axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),Ts({start:ke(1),end:o},({i:f})=>{Ze(f.greaterThanEqual(n),()=>{mv()});const m=B(r.mul(B(f))).toVar();p.addAssign(i.element(f).mul(Ac({theta:m.mul(-1),axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u}))),p.addAssign(i.element(f).mul(Ac({theta:m,axis:d,outputDirection:s,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:h,CUBEUV_MAX_MIP:u})))}),ne(p,1)}),yi=new N,Hp=new he,Wp=new he;class Zt extends du{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=cr*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ao*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return cr*2*Math.atan(Math.tan(ao*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){yi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(yi.x,yi.y).multiplyScalar(-e/yi.z),yi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(yi.x,yi.y).multiplyScalar(-e/yi.z)}getViewSize(e,t){return this.getViewBounds(e,Hp,Wp),t.subVectors(Wp,Hp)}setViewOffset(e,t,s,i,n,r){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(ao*.5*this.fov)/this.zoom,s=2*t,i=this.aspect*s,n=-.5*i;const r=this.view;if(this.view!==null&&this.view.enabled){const l=r.fullWidth,c=r.fullHeight;n+=r.offsetX*i/l,t-=r.offsetY*s/c,i*=r.width/l,s*=r.height/c}const a=this.filmOffset;a!==0&&(n+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+i,t,t-s,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class No extends ui{constructor(e=1,t=1,s=1,i=1,n=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:n,depthSegments:r};const a=this;i=Math.floor(i),n=Math.floor(n),r=Math.floor(r);const l=[],c=[],h=[],u=[];let d=0,p=0;f("z","y","x",-1,-1,s,t,e,r,n,0),f("z","y","x",1,-1,s,t,-e,r,n,1),f("x","z","y",1,1,e,s,t,i,r,2),f("x","z","y",1,-1,e,s,-t,i,r,3),f("x","y","z",1,-1,e,t,s,i,n,4),f("x","y","z",-1,-1,e,t,-s,i,n,5),this.setIndex(l),this.setAttribute("position",new Pt(c,3)),this.setAttribute("normal",new Pt(h,3)),this.setAttribute("uv",new Pt(u,2));function f(m,x,g,_,b,T,S,C,w,R,P){const z=T/w,$=S/R,q=T/2,j=S/2,X=C/2,Z=w+1,we=R+1;let de=0,ye=0;const se=new N;for(let Me=0;Me<we;Me++){const ze=Me*$-j;for(let ot=0;ot<Z;ot++){const be=ot*z-q;se[m]=be*_,se[x]=ze*b,se[g]=X,c.push(se.x,se.y,se.z),se[m]=0,se[x]=0,se[g]=C>0?1:-1,h.push(se.x,se.y,se.z),u.push(ot/w),u.push(1-Me/R),de+=1}}for(let Me=0;Me<R;Me++)for(let ze=0;ze<w;ze++){const ot=d+ze+Z*Me,be=d+ze+Z*(Me+1),at=d+(ze+1)+Z*(Me+1),Ot=d+(ze+1)+Z*Me;l.push(ot,be,Ot),l.push(be,at,Ot),ye+=6}a.addGroup(p,ye,P),p+=ye,d+=de}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new No(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}const Zn=4,$p=[.125,.215,.35,.446,.526,.582],an=20,Rc=new ku(-1,1,1,-1,0,1),EC=new Zt(90,1),jp=new ve;let Nc=null,Pc=0,Fc=0;const sn=(1+Math.sqrt(5))/2,In=1/sn,qp=[new N(-sn,In,0),new N(sn,In,0),new N(-In,0,sn),new N(In,0,sn),new N(0,sn,-In),new N(0,sn,In),new N(-1,1,-1),new N(1,1,-1),new N(-1,1,1),new N(1,1,1)],AC=new N,gy=new WeakMap,RC=[3,1,5,0,4,2],Dc=wC(Ro(),Ii("faceIndex")).normalize(),Gu=I(Dc.x,Dc.y,Dc.z);class NC{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,n={}){const{size:r=256,position:a=AC,renderTarget:l=null}=n;if(this._setSize(r),this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const h=l||this._allocateTarget();return n.renderTarget=h,this.fromSceneAsync(e,t,s,i,n),h}Nc=this._renderer.getRenderTarget(),Pc=this._renderer.getActiveCubeFace(),Fc=this._renderer.getActiveMipmapLevel();const c=l||this._allocateTarget();return c.depthBuffer=!0,this._init(c),this._sceneToCubeUV(e,s,i,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,s=.1,i=100,n={}){return this._hasInitialized===!1&&await this._renderer.init(),this.fromScene(e,t,s,i,n)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return this._hasInitialized===!1&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Xp(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Zp(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===xo||e.mapping===Ka?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Nc,Pc,Fc),e.scissorTest=!1,aa(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Nc=this._renderer.getRenderTarget(),Pc=this._renderer.getActiveCubeFace(),Fc=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize;return Yp(e,t)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Yp(e.width,e.height);const{_lodMax:t}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=PC(t)),this._blurMaterial=FC(t,e.width,e.height)}}async _compileMaterial(e){const t=new li(this._lodPlanes[0],e);await this._renderer.compile(t,Rc)}_sceneToCubeUV(e,t,s,i,n){const r=EC;r.near=t,r.far=s;const a=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,h=c.autoClear;c.getClearColor(jp),c.autoClear=!1;let u=this._backgroundBox;if(u===null){const f=new Ai({name:"PMREM.Background",side:Gt,depthWrite:!1,depthTest:!1});u=new li(new No,f)}let d=!1;const p=e.background;p?p.isColor&&(u.material.color.copy(p),e.background=null,d=!0):(u.material.color.copy(jp),d=!0),c.setRenderTarget(i),c.clear(),d&&c.render(u,r);for(let f=0;f<6;f++){const m=f%3;m===0?(r.up.set(0,a[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x+l[f],n.y,n.z)):m===1?(r.up.set(0,0,a[f]),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y+l[f],n.z)):(r.up.set(0,a[f],0),r.position.set(n.x,n.y,n.z),r.lookAt(n.x,n.y,n.z+l[f]));const x=this._cubeSize;aa(i,m*x,f>2?x:0,x,x),c.render(e,r)}c.autoClear=h,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===xo||e.mapping===Ka;i?this._cubemapMaterial===null&&(this._cubemapMaterial=Xp(e)):this._equirectMaterial===null&&(this._equirectMaterial=Zp(e));const n=i?this._cubemapMaterial:this._equirectMaterial;n.fragmentNode.value=e;const r=this._lodMeshes[0];r.material=n;const a=this._cubeSize;aa(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(r,Rc)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let n=1;n<i;n++){const r=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=qp[(i-n-1)%qp.length];this._blur(e,n-1,n,r,a)}t.autoClear=s}_blur(e,t,s,i,n){const r=this._pingPongRenderTarget;this._halfBlur(e,r,t,s,i,"latitudinal",n),this._halfBlur(r,e,s,s,i,"longitudinal",n)}_halfBlur(e,t,s,i,n,r,a){const l=this._renderer,c=this._blurMaterial;r!=="latitudinal"&&r!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=this._lodMeshes[i];u.material=c;const d=gy.get(c),p=this._sizeLods[s]-1,f=isFinite(n)?Math.PI/(2*p):2*Math.PI/(2*an-1),m=n/f,x=isFinite(n)?1+Math.floor(h*m):an;x>an&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${x} samples when the maximum is set to ${an}`);const g=[];let _=0;for(let w=0;w<an;++w){const R=w/m,P=Math.exp(-R*R/2);g.push(P),w===0?_+=P:w<x&&(_+=2*P)}for(let w=0;w<g.length;w++)g[w]=g[w]/_;e.texture.frame=(e.texture.frame||0)+1,d.envMap.value=e.texture,d.samples.value=x,d.weights.array=g,d.latitudinal.value=r==="latitudinal"?1:0,a&&(d.poleAxis.value=a);const{_lodMax:b}=this;d.dTheta.value=f,d.mipInt.value=b-s;const T=this._sizeLods[i],S=3*T*(i>b-Zn?i-b+Zn:0),C=4*(this._cubeSize-T);aa(t,S,C,3*T,2*T),l.setRenderTarget(t),l.render(u,Rc)}}function PC(o){const e=[],t=[],s=[],i=[];let n=o;const r=o-Zn+1+$p.length;for(let a=0;a<r;a++){const l=Math.pow(2,n);t.push(l);let c=1/l;a>o-Zn?c=$p[a-o+Zn-1]:a===0&&(c=0),s.push(c);const h=1/(l-2),u=-h,d=1+h,p=[u,u,d,u,d,d,u,u,d,d,u,d],f=6,m=6,x=3,g=2,_=1,b=new Float32Array(x*m*f),T=new Float32Array(g*m*f),S=new Float32Array(_*m*f);for(let w=0;w<f;w++){const R=w%3*2/3-1,P=w>2?0:-1,z=[R,P,0,R+2/3,P,0,R+2/3,P+1,0,R,P,0,R+2/3,P+1,0,R,P+1,0],$=RC[w];b.set(z,x*m*$),T.set(p,g*m*$);const q=[$,$,$,$,$,$];S.set(q,_*m*$)}const C=new ui;C.setAttribute("position",new ls(b,x)),C.setAttribute("uv",new ls(T,g)),C.setAttribute("faceIndex",new ls(S,_)),e.push(C),i.push(new li(C,null)),n>Zn&&n--}return{lodPlanes:e,sizeLods:t,sigmas:s,lodMeshes:i}}function Yp(o,e){const t={magFilter:Qt,minFilter:Qt,generateMipmaps:!1,type:rs,format:os,colorSpace:tr},s=new fn(o,e,t);return s.texture.mapping=gh,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function aa(o,e,t,s,i){o.viewport.set(e,t,s,i),o.scissor.set(e,t,s,i)}function Vu(o){const e=new it;return e.depthTest=!1,e.depthWrite=!1,e.blending=hr,e.name=`PMREM_${o}`,e}function FC(o,e,t){const s=Os(new Array(an).fill(0)),i=Q(new N(0,1,0)),n=Q(0),r=B(an),a=Q(0),l=Q(1),c=_e(null),h=Q(0),u=B(1/e),d=B(1/t),p=B(o),f={n:r,latitudinal:a,weights:s,poleAxis:i,outputDirection:Gu,dTheta:n,samples:l,envMap:c,mipInt:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=Vu("blur");return m.fragmentNode=CC({...f,latitudinal:a.equal(1)}),gy.set(m,f),m}function Xp(o){const e=Vu("cubemap");return e.fragmentNode=wo(o,Gu),e}function Zp(o){const e=Vu("equirect");return e.fragmentNode=_e(o,Vg(Gu),0),e}const Kp=new WeakMap;function DC(o){const e=Math.log2(o)-2,t=1/o;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:t,maxMip:e}}function OC(o,e,t){const s=BC(e);let i=s.get(o);if((i!==void 0?i.pmremVersion:-1)!==o.pmremVersion){const r=o.image;if(o.isCubeTexture)if(LC(r))i=t.fromCubemap(o,i);else return null;else if(UC(r))i=t.fromEquirectangular(o,i);else return null;i.pmremVersion=o.pmremVersion,s.set(o,i)}return i.texture}function BC(o){let e=Kp.get(o);return e===void 0&&(e=new WeakMap,Kp.set(o,e)),e}class IC extends nt{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new St;i.isRenderTargetTexture=!0,this._texture=_e(i),this._width=Q(0),this._height=Q(0),this._maxMip=Q(0),this.updateBeforeType=ue.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=DC(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(i.isPMREMTexture===!0?t=i:t=OC(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new NC(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this)),t=Jg.mul(I(t.x,t.y.negate(),t.z));let s=this.levelNode;return s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),MC(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function LC(o){if(o==null)return!1;let e=0;const t=6;for(let s=0;s<t;s++)o[s]!==void 0&&e++;return e===t}function UC(o){return o==null?!1:o.height>0}const yy=U(IC).setParameterLength(1,3);L(([o=Ro()],{renderer:e,material:t})=>{const s=Rg(o.mul(2).sub(1));let i;if(t.alphaToCoverage&&e.samples>1){const n=B(s.fwidth()).toVar();i=Bi(n.oneMinus(),n.add(1),s).oneMinus()}else i=Tt(s.greaterThan(1),0,1);return i});const Mo=L(({f0:o,f90:e,dotVH:t})=>{const s=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return o.mul(s.oneMinus()).add(e.mul(s))}),kC=L(({alpha:o,dotNL:e,dotNV:t})=>{const s=o.pow2(),i=e.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt()),n=t.mul(s.add(s.oneMinus().mul(e.pow2())).sqrt());return Us(.5,i.add(n).max(tS))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),zC=L(({alphaT:o,alphaB:e,dotTV:t,dotBV:s,dotTL:i,dotBL:n,dotNV:r,dotNL:a})=>{const l=a.mul(I(o.mul(t),e.mul(s),r).length()),c=r.mul(I(o.mul(i),e.mul(n),a).length());return Us(.5,l.add(c)).saturate()}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),GC=L(({alpha:o,dotNH:e})=>{const t=o.pow2(),s=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),VC=B(1/Math.PI),HC=L(({alphaT:o,alphaB:e,dotNH:t,dotTH:s,dotBH:i})=>{const n=o.mul(e),r=I(e.mul(s),o.mul(i),n.mul(t)),a=r.dot(r),l=n.div(a);return VC.mul(n.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),Qp=L(o=>{const{lightDirection:e,f0:t,f90:s,roughness:i,f:n,USE_IRIDESCENCE:r,USE_ANISOTROPY:a}=o,l=o.normalView||et,c=i.pow2(),h=e.add(je).normalize(),u=l.dot(e).clamp(),d=l.dot(je).clamp(),p=l.dot(h).clamp(),f=je.dot(h).clamp();let m=Mo({f0:t,f90:s,dotVH:f}),x,g;if(op(r)&&(m=vu.mix(m,n)),op(a)){const _=Oa.dot(e),b=Oa.dot(je),T=Oa.dot(h),S=rr.dot(e),C=rr.dot(je),w=rr.dot(h);x=zC({alphaT:Uh,alphaB:c,dotTV:b,dotBV:C,dotTL:_,dotBL:S,dotNV:d,dotNL:u}),g=HC({alphaT:Uh,alphaB:c,dotNH:p,dotTH:T,dotBH:w})}else x=kC({alpha:c,dotNL:u,dotNV:d}),g=GC({alpha:c,dotNH:p});return m.mul(x).mul(g)}),gr=L(o=>o.diffuseColor.mul(1/Math.PI)),xy=L(({roughness:o,dotNV:e})=>{const t=ne(-1,-.0275,-.572,.022),s=ne(1,.0425,1.04,-.04),i=o.mul(t).add(s),n=i.x.mul(i.x).min(e.mul(-9.28).exp2()).mul(i.x).add(i.y);return H(-1.04,1.04).mul(n).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),WC=L(({f:o,f90:e,dotVH:t})=>{const s=t.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return o.sub(I(e).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),$C=L(o=>{if(o.geometry.hasAttribute("normal")===!1)return B(0);const e=zs.dFdx().abs().max(zs.dFdy().abs());return e.x.max(e.y).max(e.z)}),_y=L(o=>{const{roughness:e}=o,t=$C();let s=e.max(.0525);return s=s.add(t),s=s.min(1),s}),jC=L(([o,e])=>{const t=o.x,s=o.y,i=o.z;let n=e.element(0).mul(.886227);return n=n.add(e.element(1).mul(2*.511664).mul(s)),n=n.add(e.element(2).mul(2*.511664).mul(i)),n=n.add(e.element(3).mul(2*.511664).mul(t)),n=n.add(e.element(4).mul(2*.429043).mul(t).mul(s)),n=n.add(e.element(5).mul(2*.429043).mul(s).mul(i)),n=n.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(e.element(7).mul(2*.429043).mul(t).mul(i)),n=n.add(e.element(8).mul(.429043).mul(fe(t,t).sub(fe(s,s)))),n});class Hu extends ui{constructor(e=1,t=32,s=16,i=0,n=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:n,thetaStart:r,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const l=Math.min(r+a,Math.PI);let c=0;const h=[],u=new N,d=new N,p=[],f=[],m=[],x=[];for(let g=0;g<=s;g++){const _=[],b=g/s;let T=0;g===0&&r===0?T=.5/t:g===s&&l===Math.PI&&(T=-.5/t);for(let S=0;S<=t;S++){const C=S/t;u.x=-e*Math.cos(i+C*n)*Math.sin(r+b*a),u.y=e*Math.cos(r+b*a),u.z=e*Math.sin(i+C*n)*Math.sin(r+b*a),f.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),x.push(C+T,1-b),_.push(c++)}h.push(_)}for(let g=0;g<s;g++)for(let _=0;_<t;_++){const b=h[g][_+1],T=h[g][_],S=h[g+1][_],C=h[g+1][_+1];(g!==0||r>0)&&p.push(b,T,C),(g!==s-1||l<Math.PI)&&p.push(T,S,C)}this.setIndex(p),this.setAttribute("position",new Pt(f,3)),this.setAttribute("normal",new Pt(m,3)),this.setAttribute("uv",new Pt(x,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Hu(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}const gs=new fu;class qC extends Li{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,n=this.nodes.getBackgroundNode(e)||e.background;let r=!1;if(n===null)i._clearColor.getRGB(gs),gs.a=i._clearColor.a;else if(n.isColor===!0)n.getRGB(gs),gs.a=1,r=!0;else if(n.isNode===!0){const l=this.get(e),c=n;gs.copy(i._clearColor);let h=l.backgroundMesh;if(h===void 0){let m=function(){n.removeEventListener("dispose",m),h.material.dispose(),h.geometry.dispose()};const d=Eu(ne(c).mul(Op),{getUV:()=>TM.mul(Bu),getTextureLevel:()=>bM});let p=ny;p=p.setZ(p.w);const f=new it;f.name="Background.material",f.side=Gt,f.depthTest=!1,f.depthWrite=!1,f.allowOverride=!1,f.fog=!1,f.lights=!1,f.vertexNode=p,f.colorNode=d,l.backgroundMeshNode=d,l.backgroundMesh=h=new li(new Hu(1,32,32),f),h.frustumCulled=!1,h.name="Background.mesh",h.onBeforeRender=function(x,g,_){this.matrixWorld.copyPosition(_.matrixWorld)},n.addEventListener("dispose",m)}const u=c.getCacheKey();l.backgroundCacheKey!==u&&(l.backgroundMeshNode.node=ne(c).mul(Op),l.backgroundMeshNode.needsUpdate=!0,h.material.needsUpdate=!0,l.backgroundCacheKey=u),t.unshift(h,h.geometry,h.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",n);const a=i.xr.getEnvironmentBlendMode();if(a==="additive"?gs.set(0,0,0,1):a==="alpha-blend"&&gs.set(0,0,0,0),i.autoClear===!0||r===!0){const l=s.clearColorValue;l.r=gs.r,l.g=gs.g,l.b=gs.b,l.a=gs.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=i.autoClearColor===!0,s.clearDepth=i.autoClearDepth===!0,s.clearStencil=i.autoClearStencil===!0}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let YC=0;class jh{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=YC++}}class XC{constructor(e,t,s,i,n,r,a,l,c,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=h,this.nodeAttributes=i,this.bindings=n,this.updateNodes=r,this.updateBeforeNodes=a,this.updateAfterNodes=l,this.observer=c,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const i=new jh(t.name,[],t.index,t);e.push(i);for(const n of t.bindings)i.bindings.push(n.clone())}else e.push(t);return e}}function by(o){const e={};for(const t in o){e[t]={};for(const s in o[t]){const i=o[t][s];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][s]=null):e[t][s]=i.clone():Array.isArray(i)?e[t][s]=i.slice():e[t][s]=i}}return e}function ZC(o){const e=[];for(let t=0;t<o.length;t++)e.push(o[t].clone());return e}const KC=`
|
|
76
76
|
void main() {
|
|
77
77
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
78
78
|
}
|
|
79
|
-
`,
|
|
79
|
+
`,QC=`
|
|
80
80
|
void main() {
|
|
81
81
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
82
82
|
}
|
|
83
|
-
`;class
|
|
83
|
+
`;class JC extends Vt{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=KC,this.fragmentShader=QC,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=by(e.uniforms),this.uniformsGroups=ZC(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const i in this.uniforms){const r=this.uniforms[i].value;r&&r.isTexture?t.uniforms[i]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[i]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[i]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[i]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[i]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[i]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[i]={type:"m4",value:r.toArray()}:t.uniforms[i]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const i in this.extensions)this.extensions[i]===!0&&(s[i]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class eE extends fn{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}const Ln=-90,Un=1;class Ty extends dt{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Zt(Ln,Un,e,t);i.layers=this.layers,this.add(i);const n=new Zt(Ln,Un,e,t);n.layers=this.layers,this.add(n);const r=new Zt(Ln,Un,e,t);r.layers=this.layers,this.add(r);const a=new Zt(Ln,Un,e,t);a.layers=this.layers,this.add(a);const l=new Zt(Ln,Un,e,t);l.layers=this.layers,this.add(l);const c=new Zt(Ln,Un,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,n,r,a,l]=t;for(const c of t)this.remove(c);if(e===Ut)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),n.up.set(0,0,-1),n.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Oi)s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),n.up.set(0,0,1),n.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[n,r,a,l,c,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,n),e.setRenderTarget(s,1,i),e.render(t,r),e.setRenderTarget(s,2,i),e.render(t,a),e.setRenderTarget(s,3,i),e.render(t,l),e.setRenderTarget(s,4,i),e.render(t,c),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=f,s.texture.needsPMREMUpdate=!0}}class tE extends eE{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Cl(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:`
|
|
84
84
|
|
|
85
85
|
varying vec3 vWorldDirection;
|
|
86
86
|
|
|
@@ -115,14 +115,14 @@ void main() {
|
|
|
115
115
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
116
116
|
|
|
117
117
|
}
|
|
118
|
-
`},i=new Ro(5,5,5),n=new RC({name:"CubemapFromEquirect",uniforms:gy(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:Vt,blending:lr});n.uniforms.tEquirect.value=t;const r=new li(i,n),a=t.minFilter;return t.minFilter===ei&&(t.minFilter=Kt),new yy(1,10,this).update(e,r),t.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const n=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(n)}}class xy extends PC{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n=new Ro(5,5,5),r=Ug(Lg),a=new it;a.colorNode=_e(t,r,0),a.side=Vt,a.blending=lr;const l=new li(n,a),c=new cu;c.add(l),t.minFilter===ei&&(t.minFilter=Kt);const h=new yy(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,c),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}}const po=new WeakMap;class FC extends nt{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=vo(null);const t=new vl;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=he.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const n=i.isTextureNode?i.value:s[i.property];if(n&&n.isTexture){const r=n.mapping;if(r===eu||r===tu){if(po.has(n)){const a=po.get(n);Zp(a,n.mapping),this._cubeTexture=a}else{const a=n.image;if(DC(a)){const l=new xy(a.height);l.fromEquirectangularTexture(t,n),Zp(l.texture,n.mapping),this._cubeTexture=l.texture,po.set(n,l.texture),n.addEventListener("dispose",_y)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function DC(o){return o==null?!1:o.height>0}function _y(o){const e=o.target;e.removeEventListener("dispose",_y);const t=po.get(e);t!==void 0&&(po.delete(e),t.dispose())}function Zp(o,e){e===eu?o.mapping=yo:e===tu&&(o.mapping=Xa)}const by=U(FC).setParameterLength(1);class El{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Qp{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class OC{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class Ty{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class BC extends Ty{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class IC{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let LC=0;class Pc{constructor(e=null){this.id=LC++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class UC{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class ki{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class kC extends ki{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class zC extends ki{constructor(e,t=new ce){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class VC extends ki{constructor(e,t=new N){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class GC extends ki{constructor(e,t=new ge){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class HC extends ki{constructor(e,t=new ve){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class WC extends ki{constructor(e,t=new ul){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class $C extends ki{constructor(e,t=new Ht){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class jC extends ki{constructor(e,t=new Ie){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class qC extends kC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class YC extends zC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class XC extends VC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZC extends GC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class QC extends HC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class KC extends WC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class JC extends $C{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class eE extends jC{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Kp=new WeakMap,tE=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),aa=o=>/e/g.test(o)?String(o).replace(/\+/g,""):(o=Number(o),o+(o%1?"":".0"));class Sy{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=Ql(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Pc,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getBindGroupsCache(){let e=Kp.get(this.renderer);return e===void 0&&(e=new vs,Kp.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new fn(e,t,s)}createCubeRenderTarget(e,t){return new xy(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let n=!0;for(const a of t)i.push(a),n=n&&a.groupNode.shared!==!0;let r;return n?(r=s.get(i),r===void 0&&(r=new Wh(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new Wh(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){const t={},s=this.bindings;for(const i of Qd)for(const n in s[i]){const r=s[i][n];(t[n]||(t[n]=[])).push(...r)}e=[];for(const i in t){const n=t[i],r=this._getBindGroup(i,n);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,s)=>t.bindings[0].groupNode.order-s.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.includes(e)===!1&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==he.NONE&&this.updateNodes.push(e.getSelf());for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==he.NONE&&this.updateBeforeNodes.push(e.getSelf()),s!==he.NONE&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Kt||e.magFilter===mh||e.magFilter===xo||e.magFilter===ei||e.minFilter===Kt||e.minFilter===mh||e.minFilter===xo||e.minFilter===ei}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}getSharedContext(){return{...this.context},this.context}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return s.cache===void 0&&(s.cache=new Pc(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,t.usageCount}generateTexture(){console.warn("Abstract function.")}generateTextureLod(){console.warn("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let n=0;n<t;n++){const r=s?s[n]:null;r!==null?i+=r.build(this,e):i+=this.generateConst(e),n<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const n of t){const{name:r,type:a}=n;s&&s[r]&&s[r].isNode?i.push(s[r].build(this,a)):i.push(this.generateConst(a))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new ve:e==="vec2"?t=new ce:e==="vec3"?t=new N:e==="vec4"&&(t=new ge)),e==="float")return aa(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${aa(t.r)}, ${aa(t.g)}, ${aa(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),n=r=>this.generateConst(i,r);if(s===2)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)} )`;if(s===3)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)} )`;if(s===4&&e!=="mat2")return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)}, ${n(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(n).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const s=this.attributes;for(const n of s)if(n.name===e)return n;const i=new Qp(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Et)return"int";if(t===Xe)return"uint"}return"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let s=z_(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return tE.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,n=e.normalized;let r;return!(e instanceof Zm)&&n!==!0&&(r=this.getTypeFromArray(s)),this.getTypeFromLength(i,r)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return s!==null?Number(s[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}addStack(){return this.stack=Ql(this.stack),this.stacks.push(ng()||this.stack),tl(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,tl(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){s=s===null?e.isGlobal(this)?this.globalCache:this.cache:s;let i=s.getData(e);return i===void 0&&(i={},s.setData(e,i)),i[t]===void 0&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(i===void 0){const n=this.uniforms.index++;i=new Qp("nodeAttribute"+n,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const n=this.getDataFromNode(e,i,this.globalCache);let r=n.structType;if(r===void 0){const a=this.structs.index++;s===null&&(s="StructType"+a),r=new UC(s,t),this.structs[i].push(r),n.structType=r}return r}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const n=this.getDataFromNode(e,s,this.globalCache);let r=n.uniform;if(r===void 0){const a=this.uniforms.index++;r=new OC(i||"nodeUniform"+a,t,e),this.uniforms[s].push(r),this.registerDeclaration(r),n.uniform=r}return r}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,n=!1){const r=this.getDataFromNode(e,i);let a=r.variable;if(a===void 0){const l=n?"_const":"_var",c=this.vars[i]||(this.vars[i]=[]),h=this.vars[l]||(this.vars[l]=0);t===null&&(t=(n?"nodeConst":"nodeVar")+h,this.vars[l]++);const u=this.getArrayCount(e);a=new Ty(t,s,n,u),n||c.push(a),this.registerDeclaration(a),r.variable=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,n=null){const r=this.getDataFromNode(e,"any");let a=r.varying;if(a===void 0){const l=this.varyings,c=l.length;t===null&&(t="nodeVarying"+c),a=new BC(t,s,i,n),l.push(a),this.registerDeclaration(a),r.varying=a}return a}get namespace(){return this.context.namespace}getOutputNamespace(){return this.getNamespace("outputNode")}getNamespace(e=""){const t=this.namespace;let s;return t?s=e?t+"_"+e:t:s=e,s}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let n=1,r=i;for(;s[r]!==void 0;)r=i+"_"+n++;n>1&&(e.name=r,console.warn(`THREE.TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${r}'.`)),s[r]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let n=i.code;if(n===void 0){const r=this.codes[s]||(this.codes[s]=[]),a=r.length;n=new IC("nodeCode"+a,t),r.push(n),i.code=n}return n}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let n=!0,r=t;for(;r;){if(i.get(r)===!0){n=!1;break}r=this.getDataFromNode(r).parentNodeBlock}if(n)for(const a of s)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),n=i.flowCodes||(i.flowCodes=[]),r=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);n.push(t),r.set(s,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`;
|
|
119
|
-
`),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new
|
|
118
|
+
`},i=new No(5,5,5),n=new JC({name:"CubemapFromEquirect",uniforms:by(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:Gt,blending:hr});n.uniforms.tEquirect.value=t;const r=new li(i,n),a=t.minFilter;return t.minFilter===ei&&(t.minFilter=Qt),new Ty(1,10,this).update(e,r),t.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const n=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(n)}}class Sy extends tE{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n=new No(5,5,5),r=Vg(Gg),a=new it;a.colorNode=_e(t,r,0),a.side=Gt,a.blending=hr;const l=new li(n,a),c=new uu;c.add(l),t.minFilter===ei&&(t.minFilter=Qt);const h=new Ty(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,c),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}}const mo=new WeakMap;class sE extends nt{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=wo(null);const t=new Cl;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ue.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const n=i.isTextureNode?i.value:s[i.property];if(n&&n.isTexture){const r=n.mapping;if(r===su||r===iu){if(mo.has(n)){const a=mo.get(n);Jp(a,n.mapping),this._cubeTexture=a}else{const a=n.image;if(iE(a)){const l=new Sy(a.height);l.fromEquirectangularTexture(t,n),Jp(l.texture,n.mapping),this._cubeTexture=l.texture,mo.set(n,l.texture),n.addEventListener("dispose",vy)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function iE(o){return o==null?!1:o.height>0}function vy(o){const e=o.target;e.removeEventListener("dispose",vy);const t=mo.get(e);t!==void 0&&(mo.delete(e),t.dispose())}function Jp(o,e){e===su?o.mapping=xo:e===iu&&(o.mapping=Ka)}const wy=U(sE).setParameterLength(1);class Nl{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class ef{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class nE{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class My{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class rE extends My{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class oE{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let aE=0;class Oc{constructor(e=null){this.id=aE++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class lE{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class ki{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class cE extends ki{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class hE extends ki{constructor(e,t=new he){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class uE extends ki{constructor(e,t=new N){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class dE extends ki{constructor(e,t=new ge){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class pE extends ki{constructor(e,t=new ve){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class fE extends ki{constructor(e,t=new fl){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class mE extends ki{constructor(e,t=new Ht){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class gE extends ki{constructor(e,t=new Ie){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class yE extends cE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class xE extends hE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _E extends uE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class bE extends dE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class TE extends pE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class SE extends fE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class vE extends mE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class wE extends gE{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const tf=new WeakMap,ME=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),la=o=>/e/g.test(o)?String(o).replace(/\+/g,""):(o=Number(o),o+(o%1?"":".0"));class Cy{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=ec(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Oc,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getBindGroupsCache(){let e=tf.get(this.renderer);return e===void 0&&(e=new vs,tf.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new fn(e,t,s)}createCubeRenderTarget(e,t){return new Sy(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let n=!0;for(const a of t)i.push(a),n=n&&a.groupNode.shared!==!0;let r;return n?(r=s.get(i),r===void 0&&(r=new jh(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new jh(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){const t={},s=this.bindings;for(const i of ep)for(const n in s[i]){const r=s[i][n];(t[n]||(t[n]=[])).push(...r)}e=[];for(const i in t){const n=t[i],r=this._getBindGroup(i,n);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,s)=>t.bindings[0].groupNode.order-s.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.includes(e)===!1&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==ue.NONE&&this.updateNodes.push(e.getSelf());for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==ue.NONE&&this.updateBeforeNodes.push(e.getSelf()),s!==ue.NONE&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Qt||e.magFilter===yh||e.magFilter===_o||e.magFilter===ei||e.minFilter===Qt||e.minFilter===yh||e.minFilter===_o||e.minFilter===ei}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}getSharedContext(){return{...this.context},this.context}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return s.cache===void 0&&(s.cache=new Oc(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,t.usageCount}generateTexture(){console.warn("Abstract function.")}generateTextureLod(){console.warn("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let n=0;n<t;n++){const r=s?s[n]:null;r!==null?i+=r.build(this,e):i+=this.generateConst(e),n<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const n of t){const{name:r,type:a}=n;s&&s[r]&&s[r].isNode?i.push(s[r].build(this,a)):i.push(this.generateConst(a))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new ve:e==="vec2"?t=new he:e==="vec3"?t=new N:e==="vec4"&&(t=new ge)),e==="float")return la(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${la(t.r)}, ${la(t.g)}, ${la(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),n=r=>this.generateConst(i,r);if(s===2)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)} )`;if(s===3)return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)} )`;if(s===4&&e!=="mat2")return`${this.getType(e)}( ${n(t.x)}, ${n(t.y)}, ${n(t.z)}, ${n(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(n).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const s=this.attributes;for(const n of s)if(n.name===e)return n;const i=new ef(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Et)return"int";if(t===Xe)return"uint"}return"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let s=hb(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return ME.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,n=e.normalized;let r;return!(e instanceof eg)&&n!==!0&&(r=this.getTypeFromArray(s)),this.getTypeFromLength(i,r)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return s!==null?Number(s[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}addStack(){return this.stack=ec(this.stack),this.stacks.push(lg()||this.stack),il(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,il(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){s=s===null?e.isGlobal(this)?this.globalCache:this.cache:s;let i=s.getData(e);return i===void 0&&(i={},s.setData(e,i)),i[t]===void 0&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e);let i=s.bufferAttribute;if(i===void 0){const n=this.uniforms.index++;i=new ef("nodeAttribute"+n,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const n=this.getDataFromNode(e,i,this.globalCache);let r=n.structType;if(r===void 0){const a=this.structs.index++;s===null&&(s="StructType"+a),r=new lE(s,t),this.structs[i].push(r),n.structType=r}return r}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const n=this.getDataFromNode(e,s,this.globalCache);let r=n.uniform;if(r===void 0){const a=this.uniforms.index++;r=new nE(i||"nodeUniform"+a,t,e),this.uniforms[s].push(r),this.registerDeclaration(r),n.uniform=r}return r}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,n=!1){const r=this.getDataFromNode(e,i);let a=r.variable;if(a===void 0){const l=n?"_const":"_var",c=this.vars[i]||(this.vars[i]=[]),h=this.vars[l]||(this.vars[l]=0);t===null&&(t=(n?"nodeConst":"nodeVar")+h,this.vars[l]++);const u=this.getArrayCount(e);a=new My(t,s,n,u),n||c.push(a),this.registerDeclaration(a),r.variable=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,n=null){const r=this.getDataFromNode(e,"any");let a=r.varying;if(a===void 0){const l=this.varyings,c=l.length;t===null&&(t="nodeVarying"+c),a=new rE(t,s,i,n),l.push(a),this.registerDeclaration(a),r.varying=a}return a}get namespace(){return this.context.namespace}getOutputNamespace(){return this.getNamespace("outputNode")}getNamespace(e=""){const t=this.namespace;let s;return t?s=e?t+"_"+e:t:s=e,s}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let n=1,r=i;for(;s[r]!==void 0;)r=i+"_"+n++;n>1&&(e.name=r,console.warn(`THREE.TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${r}'.`)),s[r]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let n=i.code;if(n===void 0){const r=this.codes[s]||(this.codes[s]=[]),a=r.length;n=new oE("nodeCode"+a,t),r.push(n),i.code=n}return n}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let n=!0,r=t;for(;r;){if(i.get(r)===!0){n=!1;break}r=this.getDataFromNode(r).parentNodeBlock}if(n)for(const a of s)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),n=i.flowCodes||(i.flowCodes=[]),r=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);n.push(t),r.set(s,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`;
|
|
119
|
+
`),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new IM,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let r=0;const a=Object.values(this);return{next:()=>({value:a[r],done:r++>=a.length})}}};for(const r of t.inputs)s[r.name]=new dv(r.type,r.name);e.layout=null;const i=e.call(s),n=this.flowStagesNode(i,t.type);return e.layout=t,n}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,n=this.declarations,r=this.cache,a=this.buildStage,l=this.stack,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new Oc,this.stack=ec();for(const h of Jd)this.setBuildStage(h),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=n,this.cache=r,this.stack=l,this.setBuildStage(a),c}getFunctionOperator(){return null}buildFunctionCode(){console.warn("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const n=this.tab,r=this.cache,a=this.shaderStage,l=this.context;this.setShaderStage(e);const c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=c;let h=null;if(this.buildStage==="generate"){const u=this.flowChildNode(t,s);i!==null&&(u.code+=`${this.tab+i} = ${u.result};
|
|
120
120
|
`),this.flowCode[e]=this.flowCode[e]+u.code,h=u}else h=t.build(this);return this.setShaderStage(a),this.cache=r,this.tab=n,this.context=l,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,s=null){return`${s!==null?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(s!==void 0)for(const i of s)t+=`${this.getVar(i.type,i.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(t!==void 0)for(const i of t)s+=i.code+`
|
|
121
|
-
`;return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:s}=this;if(t!==null){let i=s.library.fromMaterial(t);i===null&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),i=new it),i.build(this)}else this.addFlow("compute",e);for(const i of
|
|
122
|
-
`}*[Symbol.iterator](){}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class Jp{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return s===void 0&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.frameId&&e.updateBefore(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.renderId&&e.updateBefore(this)!==!1&&i.set(s,this.renderId)}else t===he.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.frameId&&e.updateAfter(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.renderId&&e.updateAfter(this)!==!1&&i.set(s,this.renderId)}else t===he.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===he.FRAME){const{frameMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.frameId&&e.update(this)!==!1&&i.set(s,this.frameId)}else if(t===he.RENDER){const{renderMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.renderId&&e.update(this)!==!1&&i.set(s,this.renderId)}else t===he.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class Gu{constructor(e,t,s=null,i="",n=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=n}}Gu.isNodeFunctionInput=!0;class sE extends mn{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:ay(this.light),lightColor:e}}}const Fc=new Ie,la=new Ie;let Ur=null;class iE extends mn{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=K(new N).setGroup(Q),this.halfWidth=K(new N).setGroup(Q),this.updateType=he.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;la.identity(),Fc.copy(t.matrixWorld),Fc.premultiply(s),la.extractRotation(Fc),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(la),this.halfHeight.value.applyMatrix4(la)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=_e(Ur.LTC_FLOAT_1),s=_e(Ur.LTC_FLOAT_2)):(t=_e(Ur.LTC_HALF_1),s=_e(Ur.LTC_HALF_2));const{colorNode:i,light:n}=this,r=oy(n);return{lightColor:i,lightPosition:r,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){Ur=e}}class Hu extends mn{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=K(0).setGroup(Q),this.penumbraCosNode=K(0).setGroup(Q),this.cutoffDistanceNode=K(0).setGroup(Q),this.decayExponentNode=K(0).setGroup(Q),this.colorNode=K(this.color).setGroup(Q)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return Bi(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return s===void 0&&(s=gM(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:n}=this,r=this.getLightVector(e),a=r.normalize(),l=a.dot(ay(n)),c=this.getSpotAttenuation(e,l),h=r.length(),u=uy({lightDistance:h,cutoffDistance:s,decayExponent:i});let d=t.mul(c).mul(u),p,f;return n.colorNode?(f=this.getLightCoord(e),p=n.colorNode(f)):n.map&&(f=this.getLightCoord(e),p=_e(n.map,f.xy).onRenderUpdate(()=>n.map)),p&&(d=f.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(p),d)),{lightColor:d,lightDirection:a}}}class nE extends Hu{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&s.isTexture===!0){const n=t.acos().mul(1/Math.PI);i=_e(s,H(n,0),0).r}else i=super.getSpotAttenuation(t);return i}}const rE=L(([o,e])=>{const t=o.abs().sub(e);return ni(vt(t,0)).add(dr(vt(t.x,t.y),0))});class oE extends Hu{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let s=1;t.map!==null&&(s=t.map.width/t.map.height),t.shadow.aspect=s}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=this.penumbraCosNode,s=this.getLightCoord(e),i=s.xyz.div(s.w),n=rE(i.xy.sub(H(.5)),H(.5)),r=Us(-1,At(1,xg(t)).sub(1));return Cg(n.mul(-2).mul(r))}}class aE extends mn{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class lE extends mn{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=ry(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=K(new ve).setGroup(Q)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=Du.dot(i).mul(.5).add(.5),a=Ve(s,t,r);e.context.irradiance.addAssign(a)}}class cE extends mn{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let s=0;s<9;s++)t.push(new N);this.lightProbe=Os(t)}update(e){const{light:t}=this;super.update(e);for(let s=0;s<9;s++)this.lightProbe.array[s].copy(t.sh.coefficients[s]).multiplyScalar(t.intensity)}setup(e){const t=SC(Du,this.lightProbe);e.context.irradiance.addAssign(t)}}const ef=new WeakMap;class hE extends _r{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const u=s.isTextureNode?s.value:t[s.property];let d=ef.get(u);d===void 0&&(d=py(u),ef.set(u,d)),s=d}const n=t.useAnisotropy===!0||t.anisotropy>0?Ov:et,r=s.context(tf(Xs,n)).mul(ic),a=s.context(uE(Ou)).mul(Math.PI).mul(ic),l=Ba(r),c=Ba(a);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);const h=e.context.lightingModel.clearcoatRadiance;if(h){const u=s.context(tf(nl,Jr)).mul(ic),d=Ba(u);h.addAssign(d)}}}const tf=(o,e)=>{let t=null;return{getUV:()=>(t===null&&(t=je.negate().reflect(e),t=o.mul(o).mix(t,e).normalize(),t=t.transformDirection(hi)),t),getTextureLevel:()=>o}},uE=o=>({getUV:()=>o,getTextureLevel:()=>B(1)});class Wu extends _r{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=by(this.envNode)}}class vy{parseFunction(){console.warn("Abstract function.")}}class $u{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}$u.isNodeFunction=!0;const dE=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,pE=/[a-z_0-9]+/ig,sf="#pragma main",fE=o=>{o=o.trim();const e=o.indexOf(sf),t=e!==-1?o.slice(e+sf.length):o,s=t.match(dE);if(s!==null&&s.length===5){const i=s[4],n=[];let r=null;for(;(r=pE.exec(i))!==null;)n.push(r);const a=[];let l=0;for(;l<n.length;){const f=n[l][0]==="const";f===!0&&l++;let m=n[l][0];m==="in"||m==="out"||m==="inout"?l++:m="";const y=n[l++][0];let g=Number.parseInt(n[l][0]);Number.isNaN(g)===!1?l++:g=null;const _=n[l++][0];a.push(new Gu(y,_,g,m,f))}const c=t.substring(s[0].length),h=s[3]!==void 0?s[3]:"",u=s[2],d=s[1]!==void 0?s[1]:"",p=e!==-1?o.slice(0,e):"";return{type:u,inputs:a,name:h,precision:d,inputsCode:i,blockCode:c,headerCode:p}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class mE extends $u{constructor(e){const{type:t,inputs:s,name:i,precision:n,inputsCode:r,blockCode:a,headerCode:l}=fE(e);super(t,s,i,n),this.inputsCode=r,this.blockCode=a,this.headerCode=l}getCode(e=this.name){let t;const s=this.blockCode;if(s!==""){const{type:i,inputsCode:n,headerCode:r,precision:a}=this;let l=`${i} ${e} ( ${n.trim()} )`;a!==""&&(l=`${a} ${l}`),t=r+l+s}else t="";return t}}class gE extends vy{parseFunction(e){return new mE(e)}}class wy extends El{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(ne(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(ne(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Se.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,n=e.context.environment;if(n)switch(t.combine){case hl:i.rgb.assign(Ve(i.rgb,i.rgb.mul(n.rgb),La.mul(nc)));break;case o_:i.rgb.assign(Ve(i.rgb,n.rgb,La.mul(nc)));break;case a_:i.rgb.addAssign(n.rgb.mul(La.mul(nc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const yE=()=>B(.25),xE=L(({dotNH:o})=>Lh.mul(B(.5)).add(1).mul(B(1/Math.PI)).mul(o.pow(Lh))),_E=L(({lightDirection:o})=>{const e=o.add(je).normalize(),t=et.dot(e).clamp(),s=je.dot(e).clamp(),i=wo({f0:Yt,f90:1,dotVH:s}),n=yE(),r=xE({dotNH:t});return i.mul(n).mul(r)});class My extends wy{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=et.dot(e).clamp().mul(t);s.directDiffuse.addAssign(n.mul(fr({diffuseColor:Se.rgb}))),this.specular===!0&&s.directSpecular.addAssign(n.mul(_E({lightDirection:e})).mul(La))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(fr({diffuseColor:Se}))),i.indirectDiffuse.mulAssign(t)}}const Cy=L(o=>{const{dotNV:e,specularColor:t,specularF90:s,roughness:i}=o,n=fy({dotNV:e,roughness:i});return t.mul(n.x).add(s.mul(n.y))}),bE=L(({roughness:o,dotNH:e})=>{const t=o.pow2(),s=B(1).div(t),n=e.pow2().oneMinus().max(.0078125);return B(2).add(s).mul(n.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),TE=L(({dotNV:o,dotNL:e})=>B(1).div(B(4).mul(e.add(o).sub(e.mul(o))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),SE=L(({lightDirection:o})=>{const e=o.add(je).normalize(),t=et.dot(o).clamp(),s=et.dot(je).clamp(),i=et.dot(e).clamp(),n=bE({roughness:bu,dotNH:i}),r=TE({dotNV:s,dotNL:t});return Yn.mul(n).mul(r)}),vE=L(({N:o,V:e,roughness:t})=>{const n=.0078125,r=o.dot(e).saturate(),a=H(t,r.oneMinus().sqrt());return a.assign(a.mul(.984375).add(n)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),wE=L(({f:o})=>{const e=o.length();return vt(e.mul(e).add(o.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),ca=L(({v1:o,v2:e})=>{const t=o.dot(e),s=t.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),r=i.div(n),a=t.greaterThan(0).select(r,vt(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(r));return o.cross(e).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),nf=L(({N:o,V:e,P:t,mInv:s,p0:i,p1:n,p2:r,p3:a})=>{const l=n.sub(i).toVar(),c=a.sub(i).toVar(),h=l.cross(c),u=I().toVar();return Ze(h.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(o.mul(e.dot(o))).normalize(),p=o.cross(d).negate(),f=s.mul(Ft(d,p,o).transpose()).toVar(),m=f.mul(i.sub(t)).normalize().toVar(),y=f.mul(n.sub(t)).normalize().toVar(),g=f.mul(r.sub(t)).normalize().toVar(),_=f.mul(a.sub(t)).normalize().toVar(),b=I(0).toVar();b.addAssign(ca({v1:m,v2:y})),b.addAssign(ca({v1:y,v2:g})),b.addAssign(ca({v1:g,v2:_})),b.addAssign(ca({v1:_,v2:m})),u.assign(I(wE({f:b})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),rf=L(([o,e,t,s,i])=>{const n=I(Eg(e.negate(),To(o),Us(1,s))),r=I(ni(i[0].xyz),ni(i[1].xyz),ni(i[2].xyz));return To(n).mul(t.mul(r))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),ME=L(([o,e])=>o.mul(ai(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),CE=Wg(),EE=Wg(),of=L(([o,e,t],{material:s})=>{const n=(s.side===Vt?CE:EE).sample(o),r=ii(kh.x).mul(ME(e,t));return Xw(n,r)}),af=L(([o,e,t])=>(Ze(t.notEqual(0),()=>{const s=yg(e).negate().div(t);return gg(s.negate().mul(o))}),I(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),AE=L(([o,e,t,s,i,n,r,a,l,c,h,u,d,p,f])=>{let m,y;if(f){m=ne().toVar(),y=I().toVar();const S=h.sub(1).mul(f.mul(.025)),C=I(h.sub(S),h,h.add(S));Ts({start:0,end:3},({i:w})=>{const R=C.element(w),P=rf(o,e,u,R,a),z=r.add(P),$=c.mul(l.mul(ne(z,1))),q=H($.xy.div($.w)).toVar();q.addAssign(1),q.divAssign(2),q.assign(H(q.x,q.y.oneMinus()));const j=of(q,t,R);m.element(w).assign(j.element(w)),m.a.addAssign(j.a),y.element(w).assign(s.element(w).mul(af(ni(P),d,p).element(w)))}),m.a.divAssign(3)}else{const S=rf(o,e,u,h,a),C=r.add(S),w=c.mul(l.mul(ne(C,1))),R=H(w.xy.div(w.w)).toVar();R.addAssign(1),R.divAssign(2),R.assign(H(R.x,R.y.oneMinus())),m=of(R,t,h),y=s.mul(af(ni(S),d,p))}const g=y.rgb.mul(m.rgb),_=o.dot(e).clamp(),b=I(Cy({dotNV:_,specularColor:i,specularF90:n,roughness:t})),T=y.r.add(y.g,y.b).div(3);return ne(b.oneMinus().mul(g),m.a.oneMinus().mul(T).oneMinus())}),RE=Ft(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),NE=o=>{const e=o.sqrt();return I(1).add(e).div(I(1).sub(e))},lf=(o,e)=>o.sub(e).div(o.add(e)).pow2(),PE=(o,e)=>{const t=o.mul(2*Math.PI*1e-9),s=I(54856e-17,44201e-17,52481e-17),i=I(1681e3,1795300,2208400),n=I(43278e5,93046e5,66121e5),r=B(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let a=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(n).exp());return a=I(a.x.add(r),a.y,a.z).div(10685e-11),RE.mul(a)},FE=L(({outsideIOR:o,eta2:e,cosTheta1:t,thinFilmThickness:s,baseF0:i})=>{const n=Ve(o,e,Bi(0,.03,s)),a=o.div(n).pow2().mul(t.pow2().oneMinus()).oneMinus();Ze(a.lessThan(0),()=>I(1));const l=a.sqrt(),c=lf(n,o),h=wo({f0:c,f90:1,dotVH:t}),u=h.oneMinus(),d=n.lessThan(o).select(Math.PI,0),p=B(Math.PI).sub(d),f=NE(i.clamp(0,.9999)),m=lf(f,n.toVec3()),y=wo({f0:m,f90:1,dotVH:l}),g=I(f.x.lessThan(n).select(Math.PI,0),f.y.lessThan(n).select(Math.PI,0),f.z.lessThan(n).select(Math.PI,0)),_=n.mul(s,l,2),b=I(p).add(g),T=h.mul(y).clamp(1e-5,.9999),S=T.sqrt(),C=u.pow2().mul(y).div(I(1).sub(T)),R=h.add(C).toVar(),P=C.sub(u).toVar();return Ts({start:1,end:2,condition:"<=",name:"m"},({m:z})=>{P.mulAssign(S);const $=PE(B(z).mul(_),B(z).mul(b)).mul(2);R.addAssign(P.mul($))}),R.max(I(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),DE=L(({normal:o,viewDir:e,roughness:t})=>{const s=o.dot(e).saturate(),i=t.pow2(),n=Tt(t.lessThan(.25),B(-339.2).mul(i).add(B(161.4).mul(t)).sub(25.9),B(-8.48).mul(i).add(B(14.3).mul(t)).sub(9.95)),r=Tt(t.lessThan(.25),B(44).mul(i).sub(B(23.7).mul(t)).add(3.26),B(1.97).mul(i).sub(B(3.27).mul(t)).add(.72));return Tt(t.lessThan(.25),0,B(.1).mul(t).sub(.025)).add(n.mul(s).add(r).exp()).mul(1/Math.PI).saturate()}),Dc=I(.04),Oc=B(1);class Ey extends El{constructor(e=!1,t=!1,s=!1,i=!1,n=!1,r=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=n,this.dispersion=r,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=I().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=I().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=I().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=I().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=I().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=et.dot(je).clamp();this.iridescenceFresnel=FE({outsideIOR:B(1),eta2:cg,cosTheta1:t,thinFilmThickness:hg,baseF0:Yt}),this.iridescenceF0=bC({f:this.iridescenceFresnel,f90:1,dotVH:t})}if(this.transmission===!0){const t=So,s=QS.sub(So).normalize(),i=Ou,n=e.context;n.backdrop=AE(i,s,Xs,Se,Yt,rl,t,dn,hi,Fu,Da,ug,pg,dg,this.dispersion?fg:null),n.backdropAlpha=Uh,Se.a.mulAssign(Ve(1,n.backdrop.a,Uh))}super.start(e)}computeMultiscattering(e,t,s){const i=et.dot(je).clamp(),n=fy({roughness:Xs,dotNV:i}),a=(this.iridescenceF0?Tu.mix(Yt,this.iridescenceF0):Yt).mul(n.x).add(s.mul(n.y)),c=n.x.add(n.y).oneMinus(),h=Yt.add(Yt.oneMinus().mul(.047619)),u=a.mul(h).div(c.mul(h).oneMinus());e.addAssign(a),t.addAssign(u.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=et.dot(e).clamp().mul(t);if(this.sheen===!0&&this.sheenSpecularDirect.addAssign(n.mul(SE({lightDirection:e}))),this.clearcoat===!0){const a=Jr.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(a.mul(Xp({lightDirection:e,f0:Dc,f90:Oc,roughness:nl,normalView:Jr})))}s.directDiffuse.addAssign(n.mul(fr({diffuseColor:Se.rgb}))),s.directSpecular.addAssign(n.mul(Xp({lightDirection:e,f0:Yt,f90:1,roughness:Xs,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:n,ltc_1:r,ltc_2:a}){const l=t.add(s).sub(i),c=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),d=et,p=je,f=st.toVar(),m=vE({N:d,V:p,roughness:Xs}),y=r.sample(m).toVar(),g=a.sample(m).toVar(),_=Ft(I(y.x,0,y.y),I(0,1,0),I(y.z,0,y.w)).toVar(),b=Yt.mul(g.x).add(Yt.oneMinus().mul(g.y)).toVar();n.directSpecular.addAssign(e.mul(b).mul(nf({N:d,V:p,P:f,mInv:_,p0:l,p1:c,p2:h,p3:u}))),n.directDiffuse.addAssign(e.mul(Se).mul(nf({N:d,V:p,P:f,mInv:Ft(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:h,p3:u})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(t.mul(fr({diffuseColor:Se})))}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(s.mul(Yn,DE({normal:et,viewDir:je,roughness:bu}))),this.clearcoat===!0){const h=Jr.dot(je).clamp(),u=Cy({dotNV:h,specularColor:Dc,specularF90:Oc,roughness:nl});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(u))}const n=I().toVar("singleScattering"),r=I().toVar("multiScattering"),a=s.mul(1/Math.PI);this.computeMultiscattering(n,r,rl);const l=n.add(r),c=Se.mul(l.r.max(l.g).max(l.b).oneMinus());i.indirectSpecular.addAssign(t.mul(n)),i.indirectSpecular.addAssign(r.mul(a)),i.indirectDiffuse.addAssign(c.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,n=et.dot(je).clamp().add(t),r=Xs.mul(-16).oneMinus().negate().exp2(),a=t.sub(n.pow(r).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(a)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const s=Jr.dot(je).clamp(),i=wo({dotVH:s,f0:Dc,f90:Oc}),n=t.mul(Bh.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Bh));t.assign(n)}if(this.sheen===!0){const s=Yn.r.max(Yn.g).max(Yn.b).mul(.157).oneMinus(),i=t.mul(s).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(i)}}}const cf=new WeakMap,Ms=[],$i=[];class OE extends Li{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Jp,this.nodeBuilderCache=new Map,this.callHashCache=new vs,this.groupsData=new vs,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===ag.name)return!0;if(s===Q.name){const n=this.get(e),r=this.nodeFrame.renderId;return n.renderId!==r?(n.renderId=r,!0):!1}if(s===oT.name){const n=this.get(e),r=this.nodeFrame.frameId;return n.frameId!==r?(n.frameId=r,!0):!1}Ms[0]=t,Ms[1]=e;let i=this.groupsData.get(Ms);return i===void 0&&this.groupsData.set(Ms,i={}),Ms.length=0,i.version!==t.version?(i.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const{nodeBuilderCache:i}=this,n=this.getForRenderCacheKey(e);if(s=i.get(n),s===void 0){const r=this.backend.createNodeBuilder(e.object,this.renderer);r.scene=e.scene,r.material=e.material,r.camera=e.camera,r.context.material=e.material,r.lightsNode=e.lightsNode,r.environmentNode=this.getEnvironmentNode(e.scene),r.fogNode=this.getFogNode(e.scene),r.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&r.enableMultiview(),r.build(),s=this._createNodeBuilderState(r),i.set(n,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new MC(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Ms[0]=e,Ms[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Ms)||{};if(i.callId!==s){const n=this.getEnvironmentNode(e),r=this.getFogNode(e);t&&$i.push(t.getCacheKey(!0)),n&&$i.push(n.getCacheKey()),r&&$i.push(r.getCacheKey()),$i.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),$i.push(this.renderer.shadowMap.enabled?1:0),i.callId=s,i.cacheKey=lu($i),this.callHashCache.set(Ms,i),$i.length=0}return Ms.length=0,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==s||i){const n=this.getCacheNode("background",s,()=>{if(s.isCubeTexture===!0||s.mapping===eu||s.mapping===tu||s.mapping===fh){if(e.backgroundBlurriness>0||s.mapping===fh)return py(s);{let r;return s.isCubeTexture===!0?r=vo(s):r=_e(s),by(r)}}else{if(s.isTexture===!0)return _e(s,nr.flipY()).setUpdateMatrix(!0);s.isColor!==!0&&console.error("WebGPUNodes: Unsupported background configuration.",s)}},i);t.backgroundNode=n,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const n=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let r=n.get(t);return(r===void 0||i)&&(r=s(),n.set(t,r)),r}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const i=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const n=Be("color","color",s).setGroup(Q),r=Be("density","float",s).setGroup(Q);return Dp(n,fM(r))}else if(s.isFog){const n=Be("color","color",s).setGroup(Q),r=Be("near","float",s).setGroup(Q),a=Be("far","float",s).setGroup(Q);return Dp(n,pM(r,a))}else console.error("THREE.Renderer: Unsupported fog configuration.",s)});t.fogNode=i,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const i=this.getCacheNode("environment",s,()=>{if(s.isCubeTexture===!0)return vo(s);if(s.isTexture===!0)return _e(s);console.error("Nodes: Unsupported environment configuration.",s)});t.environmentNode=i,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,n=null){const r=this.nodeFrame;return r.renderer=e,r.scene=t,r.object=s,r.camera=i,r.material=n,r}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return cf.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?eM(e,I(nr,xl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):_e(e,nr).renderOutput(t.toneMapping,t.currentColorSpace);return cf.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const i of s.updateNodes)t.updateNode(i)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const i of s.updateNodes)t.updateNode(i)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Jp,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Bc=new Mi;class al{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ht,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let n=0;n<i;n++){Bc.copy(e[n]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[s+n],a=Bc.normal;r.x=-a.x,r.y=-a.y,r.z=-a.z,r.w=Bc.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,n=i.length;let r,a;if(this.clipIntersection?(r=this.intersectionPlanes,a=e.intersectionPlanes.length):(r=this.unionPlanes,a=e.unionPlanes.length),r.length!==a+n){r.length=a+n;for(let l=0;l<n;l++)r[a+l]=new ge;s=!0}this.projectPlanes(i,r,a),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new al(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class BE{constructor(e,t){this.bundleGroup=e,this.camera=t}}const kr=[];class IE{constructor(){this.bundles=new vs}get(e,t){const s=this.bundles;kr[0]=e,kr[1]=t;let i=s.get(kr);return i===void 0&&(i=new BE(e,t),s.set(kr,i)),kr.length=0,i}dispose(){this.bundles=new vs}}class Ay{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(s!==null){t=new s;for(const i in e)t[i]=e[i]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t)){console.warn(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}addClass(e,t,s){if(s.has(t)){console.warn(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}const LE=new ly,zr=[];class UE extends vs{constructor(){super()}createNode(e=[]){return new ly().setLights(e)}getNode(e,t){if(e.isQuadMesh)return LE;zr[0]=e,zr[1]=t;let s=this.get(zr);return s===void 0&&(s=this.createNode(),this.set(zr,s)),zr.length=0,s}}class kE extends Zt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class ha extends dt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const zE={type:"move"};class VE{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ha,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 ha,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ha,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N),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){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}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,s){let i=null,n=null,r=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const m of e.hand.values()){const y=t.getJointPose(m,s),g=this._getHandJoint(c,m);y!==null&&(g.matrix.fromArray(y.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=y.radius),g.visible=y!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,f=.005;c.inputState.pinching&&d>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(n=t.getPose(e.gripSpace,s),n!==null&&(l.matrix.fromArray(n.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,n.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(n.linearVelocity)):l.hasLinearVelocity=!1,n.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(n.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,s),i===null&&n!==null&&(i=n),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(zE)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=n!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new ha;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class to extends fn{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this.hasExternalTextures=!1,this.autoAllocateDepthBuffer=!0}copy(e){return super.copy(e),this.hasExternalTextures=e.hasExternalTextures,this.autoAllocateDepthBuffer=e.autoAllocateDepthBuffer,this}}class ju extends ui{constructor(e=1,t=1,s=1,i=32,n=1,r=!1,a=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:n,openEnded:r,thetaStart:a,thetaLength:l};const c=this;i=Math.floor(i),n=Math.floor(n);const h=[],u=[],d=[],p=[];let f=0;const m=[],y=s/2;let g=0;_(),r===!1&&(e>0&&b(!0),t>0&&b(!1)),this.setIndex(h),this.setAttribute("position",new Pt(u,3)),this.setAttribute("normal",new Pt(d,3)),this.setAttribute("uv",new Pt(p,2));function _(){const T=new N,S=new N;let C=0;const w=(t-e)/s;for(let R=0;R<=n;R++){const P=[],z=R/n,$=z*(t-e)+e;for(let q=0;q<=i;q++){const j=q/i,X=j*l+a,Z=Math.sin(X),we=Math.cos(X);S.x=$*Z,S.y=-z*s+y,S.z=$*we,u.push(S.x,S.y,S.z),T.set(Z,w,we).normalize(),d.push(T.x,T.y,T.z),p.push(j,1-z),P.push(f++)}m.push(P)}for(let R=0;R<i;R++)for(let P=0;P<n;P++){const z=m[P][R],$=m[P+1][R],q=m[P+1][R+1],j=m[P][R+1];(e>0||P!==0)&&(h.push(z,$,j),C+=3),(t>0||P!==n-1)&&(h.push($,q,j),C+=3)}c.addGroup(g,C,0),g+=C}function b(T){const S=f,C=new ce,w=new N;let R=0;const P=T===!0?e:t,z=T===!0?1:-1;for(let q=1;q<=i;q++)u.push(0,y*z,0),d.push(0,z,0),p.push(.5,.5),f++;const $=f;for(let q=0;q<=i;q++){const X=q/i*l+a,Z=Math.cos(X),we=Math.sin(X);w.x=P*we,w.y=y*z,w.z=P*Z,u.push(w.x,w.y,w.z),d.push(0,z,0),C.x=Z*.5+.5,C.y=we*.5*z+.5,p.push(C.x,C.y),f++}for(let q=0;q<i;q++){const j=S+q,X=$+q;T===!0?h.push(X,X+1,j):h.push(X+1,X,j),R+=3}c.addGroup(g,R,T===!0?1:2),g+=R}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ju(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class qu extends ui{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const n=e/2,r=t/2,a=Math.floor(s),l=Math.floor(i),c=a+1,h=l+1,u=e/a,d=t/l,p=[],f=[],m=[],y=[];for(let g=0;g<h;g++){const _=g*d-r;for(let b=0;b<c;b++){const T=b*u-n;f.push(T,-_,0),m.push(0,0,1),y.push(b/a),y.push(1-g/l)}}for(let g=0;g<l;g++)for(let _=0;_<a;_++){const b=_+c*g,T=_+c*(g+1),S=_+1+c*(g+1),C=_+1+c*g;p.push(b,T,C),p.push(T,S,C)}this.setIndex(p),this.setAttribute("position",new Pt(f,3)),this.setAttribute("normal",new Pt(m,3)),this.setAttribute("uv",new Pt(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new qu(e.width,e.height,e.widthSegments,e.heightSegments)}}const hf=new N,uf=new N;class GE extends pn{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Zt,this._cameraL.viewport=new ge,this._cameraR=new Zt,this._cameraR.viewport=new ge,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new kE,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._frameBufferTargets=null,this._createXRLayer=YE.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ce,this._onSessionEvent=$E.bind(this),this._onSessionEnd=jE.bind(this),this._onInputSourcesChange=qE.bind(this),this._onAnimationFrame=XE.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._useLayers=typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(!(this._glProjLayer===null&&this._glBaseLayer===null))return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&console.warn("THREE.XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,n,r,a,l={}){const c=new qu(e,t),h=new to(n,r,{format:os,type:Nt,depthTexture:new Is(n,r,l.stencil?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?ti:Bs),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h.autoAllocateDepthBuffer=!0;const u=new Ai({color:16777215,side:Ks});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const d=new li(c,u);d.position.copy(s),d.quaternion.copy(i);const p={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:n,pixelheight:r,plane:d,material:u,rendercall:a,renderTarget:h};if(this._layers.push(p),this._session!==null){p.plane.material=new Ai({color:16777215,side:Ks}),p.plane.material.blending=oo,p.plane.material.blendEquation=bs,p.plane.material.blendSrc=vi,p.plane.material.blendDst=vi,p.xrlayer=this._createXRLayer(p);const f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else h.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,n,r,a,l,c={}){const h=new ju(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new to(r,a,{format:os,type:Nt,depthTexture:new Is(r,a,c.stencil?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?ti:Bs),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u.autoAllocateDepthBuffer=!0;const d=new Ai({color:16777215,side:Vt});d.map=u.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new li(h,d);p.position.copy(i),p.quaternion.copy(n);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:n,pixelwidth:r,pixelheight:a,plane:p,material:d,rendercall:l,renderTarget:u};if(this._layers.push(f),this._session!==null){f.plane.material=new Ai({color:16777215,side:Vt}),f.plane.material.blending=oo,f.plane.material.blendEquation=bs,f.plane.material.blendSrc=vi,f.plane.material.blendDst=vi,f.xrlayer=this._createXRLayer(f);const m=this._session.renderState.layers;m.unshift(f.xrlayer),this._session.updateRenderState({layers:m})}else u.isXRRenderTarget=!1;return p}renderLayers(){const e=new N,t=new gr,s=this._renderer,i=this.isPresenting,n=s.getOutputRenderTarget(),r=s._frameBufferTarget;this.isPresenting=!1;const a=new ce;s.getSize(a);const l=s._quad;for(const c of this._layers)if(c.renderTarget.isXRRenderTarget=this._session!==null,c.renderTarget.hasExternalTextures=c.renderTarget.isXRRenderTarget,c.renderTarget.isXRRenderTarget&&this._supportsLayers){c.xrlayer.transform=new XRRigidTransform(c.plane.getWorldPosition(e),c.plane.getWorldQuaternion(t));const h=this._glBinding.getSubImage(c.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(c.renderTarget,h.colorTexture,void 0),s._setXRLayerSize(c.renderTarget.width,c.renderTarget.height),s.setOutputRenderTarget(c.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:u,quad:d}=this._frameBufferTargets.get(c.renderTarget)||{frameBufferTarget:null,quad:null};u?(s._frameBufferTarget=u,s._quad=d):(s._quad=new Uu(new it),this._frameBufferTargets.set(c.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),c.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(c.renderTarget),c.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(n),s._frameBufferTarget=r,s._setXRLayerSize(a.x,a.y),s._quad=l,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,n=i.getContextAttributes();if(this._session=e,e!==null){if(s.isWebGPUBackend===!0)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._useLayers===!0){let r=null,a=null,l=null;t.depth&&(l=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,r=t.stencil?ti:Bs,a=t.stencil?Fi:Xe);const c={colorFormat:i.RGBA8,depthFormat:l,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(c.textureType="texture-array",this._useMultiview=!0);const h=new XRWebGLBinding(e,i),u=h.createProjectionLayer(c),d=[u];this._glBinding=h,this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const p=this._useMultiview?2:1,f=new Is(u.textureWidth,u.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,r,p);if(this._xrRenderTarget=new to(u.textureWidth,u.textureHeight,{format:os,type:Nt,colorSpace:t.outputColorSpace,depthTexture:f,stencilBuffer:t.stencil,samples:n.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget.hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const m of this._layers)m.plane.material=new Ai({color:16777215,side:m.type==="cylinder"?Vt:Ks}),m.plane.material.blending=oo,m.plane.material.blendEquation=bs,m.plane.material.blendSrc=vi,m.plane.material.blendDst=vi,m.xrlayer=this._createXRLayer(m),d.unshift(m.xrlayer);e.updateRenderState({layers:d})}else{const r={antialias:t.samples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},a=new XRWebGLLayer(e,i,r);this._glBaseLayer=a,e.updateRenderState({baseLayer:a}),t.setPixelRatio(1),t._setXRLayerSize(a.framebufferWidth,a.framebufferHeight),this._xrRenderTarget=new to(a.framebufferWidth,a.framebufferHeight,{format:os,type:Nt,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:a.ignoreDepthValues===!1,resolveStencilBuffer:a.ignoreDepthValues===!1}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(t===null)return;const s=e.near,i=e.far,n=this._cameraXR,r=this._cameraL,a=this._cameraR;n.near=a.near=r.near=s,n.far=a.far=r.far=i,n.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==n.near||this._currentDepthFar!==n.far)&&(t.updateRenderState({depthNear:n.near,depthFar:n.far}),this._currentDepthNear=n.near,this._currentDepthFar=n.far),r.layers.mask=e.layers.mask|2,a.layers.mask=e.layers.mask|4,n.layers.mask=r.layers.mask|a.layers.mask;const l=e.parent,c=n.cameras;df(n,l);for(let h=0;h<c.length;h++)df(c[h],l);c.length===2?HE(n,r,a):n.projectionMatrix.copy(r.projectionMatrix),WE(e,n,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new VE,this._controllers[e]=t),t}}function HE(o,e,t){hf.setFromMatrixPosition(e.matrixWorld),uf.setFromMatrixPosition(t.matrixWorld);const s=hf.distanceTo(uf),i=e.projectionMatrix.elements,n=t.projectionMatrix.elements,r=i[14]/(i[10]-1),a=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],h=(i[8]-1)/i[0],u=(n[8]+1)/n[0],d=r*h,p=r*u,f=s/(-h+u),m=f*-h;if(e.matrixWorld.decompose(o.position,o.quaternion,o.scale),o.translateX(m),o.translateZ(f),o.matrixWorld.compose(o.position,o.quaternion,o.scale),o.matrixWorldInverse.copy(o.matrixWorld).invert(),i[10]===-1)o.projectionMatrix.copy(e.projectionMatrix),o.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const y=r+f,g=a+f,_=d-m,b=p+(s-m),T=l*a/g*y,S=c*a/g*y;o.projectionMatrix.makePerspective(_,b,T,S,y,g),o.projectionMatrixInverse.copy(o.projectionMatrix).invert()}}function df(o,e){e===null?o.matrixWorld.copy(o.matrix):o.matrixWorld.multiplyMatrices(e.matrixWorld,o.matrix),o.matrixWorldInverse.copy(o.matrixWorld).invert()}function WE(o,e,t){t===null?o.matrix.copy(e.matrixWorld):(o.matrix.copy(t.matrixWorld),o.matrix.invert(),o.matrix.multiply(e.matrixWorld)),o.matrix.decompose(o.position,o.quaternion,o.scale),o.updateMatrixWorld(!0),o.projectionMatrix.copy(e.projectionMatrix),o.projectionMatrixInverse.copy(e.projectionMatrixInverse),o.isPerspectiveCamera&&(o.fov=ar*2*Math.atan(1/o.projectionMatrix.elements[5]),o.zoom=1)}function $E(o){const e=this._controllerInputSources.indexOf(o.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const s=this.getReferenceSpace();t.update(o.inputSource,o.frame,s),t.dispatchEvent({type:o.type,data:o.inputSource})}}function jE(){const o=this._session,e=this._renderer;o.removeEventListener("select",this._onSessionEvent),o.removeEventListener("selectstart",this._onSessionEvent),o.removeEventListener("selectend",this._onSessionEvent),o.removeEventListener("squeeze",this._onSessionEvent),o.removeEventListener("squeezestart",this._onSessionEvent),o.removeEventListener("squeezeend",this._onSessionEvent),o.removeEventListener("end",this._onSessionEnd),o.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const s=this._controllerInputSources[t];s!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(s))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._session=null,this._xrRenderTarget=null,this._supportsLayers===!0)for(const t of this._layers)t.renderTarget=new to(t.pixelwidth,t.pixelheight,{format:os,type:Nt,depthTexture:new Is(t.pixelwidth,t.pixelheight,t.stencilBuffer?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?ti:Bs),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function qE(o){const e=this._controllers,t=this._controllerInputSources;for(let s=0;s<o.removed.length;s++){const i=o.removed[s],n=t.indexOf(i);n>=0&&(t[n]=null,e[n].disconnect(i))}for(let s=0;s<o.added.length;s++){const i=o.added[s];let n=t.indexOf(i);if(n===-1){for(let a=0;a<e.length;a++)if(a>=t.length){t.push(i),n=a;break}else if(t[a]===null){t[a]=i,n=a;break}if(n===-1)break}const r=e[n];r&&r.connect(i)}}function YE(o){return o.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(o.translation,o.quaternion),width:o.width/2,height:o.height/2,space:this._referenceSpace,viewPixelWidth:o.pixelwidth,viewPixelHeight:o.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(o.translation,o.quaternion),radius:o.radius,centralAngle:o.centralAngle,aspectRatio:o.aspectRatio,space:this._referenceSpace,viewPixelWidth:o.pixelwidth,viewPixelHeight:o.pixelheight,clearOnAccess:!1})}function XE(o,e){if(e===void 0)return;const t=this._cameraXR,s=this._renderer,i=s.backend,n=this._glBaseLayer,r=this.getReferenceSpace(),a=e.getViewerPose(r);if(this._xrFrame=e,a!==null){const l=a.views;this._glBaseLayer!==null&&i.setXRTarget(n.framebuffer);let c=!1;l.length!==t.cameras.length&&(t.cameras.length=0,c=!0);for(let h=0;h<l.length;h++){const u=l[h];let d;if(this._useLayers===!0){const f=this._glBinding.getViewSubImage(this._glProjLayer,u);d=f.viewport,h===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,f.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:f.depthStencilTexture)}else d=n.getViewport(u);let p=this._cameras[h];p===void 0&&(p=new Zt,p.layers.enable(h),p.viewport=new ge,this._cameras[h]=p),p.matrix.fromArray(u.transform.matrix),p.matrix.decompose(p.position,p.quaternion,p.scale),p.projectionMatrix.fromArray(u.projectionMatrix),p.projectionMatrixInverse.copy(p.projectionMatrix).invert(),p.viewport.set(d.x,d.y,d.width,d.height),h===0&&(t.matrix.copy(p.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),c===!0&&t.cameras.push(p)}s.setOutputRenderTarget(this._xrRenderTarget)}for(let l=0;l<this._controllers.length;l++){const c=this._controllerInputSources[l],h=this._controllers[l];c!==null&&h!==void 0&&h.update(c,e,r)}this._currentAnimationLoop&&this._currentAnimationLoop(o,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}const ji=new yl,ua=new N;class Yu{constructor(e=new Mi,t=new Mi,s=new Mi,i=new Mi,n=new Mi,r=new Mi){this.planes=[e,t,s,i,n,r]}set(e,t,s,i,n,r){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(n),a[5].copy(r),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=Ut){const s=this.planes,i=e.elements,n=i[0],r=i[1],a=i[2],l=i[3],c=i[4],h=i[5],u=i[6],d=i[7],p=i[8],f=i[9],m=i[10],y=i[11],g=i[12],_=i[13],b=i[14],T=i[15];if(s[0].setComponents(l-n,d-c,y-p,T-g).normalize(),s[1].setComponents(l+n,d+c,y+p,T+g).normalize(),s[2].setComponents(l+r,d+h,y+f,T+_).normalize(),s[3].setComponents(l-r,d-h,y-f,T-_).normalize(),s[4].setComponents(l-a,d-u,y-m,T-b).normalize(),t===Ut)s[5].setComponents(l+a,d+u,y+m,T+b).normalize();else if(t===Oi)s[5].setComponents(a,u,m,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ji.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ji.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ji)}intersectsSprite(e){return ji.center.set(0,0,0),ji.radius=.7071067811865476,ji.applyMatrix4(e.matrixWorld),this.intersectsSphere(ji)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let n=0;n<6;n++)if(t[n].distanceToPoint(s)<i)return!1;return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(ua.x=i.normal.x>0?e.max.x:e.min.x,ua.y=i.normal.y>0?e.max.y:e.min.y,ua.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ua)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Cs=new Ie,Es=new Yu;class Xu{constructor(){this.coordinateSystem=Ut}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.containsPoint(e))return!0}return!1}clone(){return new Xu}}const pf=new cu,da=new ce,Ic=new ge,Lc=new Yu,Uc=new Xu,pa=new Ie,xi=new ge;class ZE{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:n=!0,stencil:r=!1,antialias:a=!1,samples:l=0,getFallback:c=null,colorBufferType:h=rs,multiview:u=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=l||a===!0?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Xt,this.toneMapping=Kn,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=r,this.info=new J_,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new Ay,this.lighting=new UE,this._getFallback=c,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ge(0,0,this._width,this._height),this._scissor=new ge(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new Uu(new it),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const d=this.alpha===!0?0:1;this._clearColor=new du(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._colorBufferType=h,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:i_},this.xr=new GE(this,u),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,f,m)=>{await this.compileAsync(p,f);const y=this._renderLists.get(p,f),g=this._renderContexts.get(p,f,this._renderTarget),_=p.overrideMaterial||m.material,b=this._objects.get(m,_,p,f,y.lightsNode,g,g.clippingContext),{fragmentShader:T,vertexShader:S}=b.getNodeBuilderState();return{fragmentShader:T,vertexShader:S}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=s=this._getFallback(i),await s.init(this)}catch(n){t(n);return}else{t(i);return}}this._nodes=new OE(this,s),this._animation=new Kx(this._nodes,this.info),this._attributes=new X_(s),this._background=new vC(this,this._nodes),this._geometries=new K_(this._attributes,this.info),this._textures=new Sb(this,s,this.info),this._pipelines=new ib(s,this._nodes),this._bindings=new nb(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new j_(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new ab(this.lighting),this._bundles=new IE,this._renderContexts=new yb,this._animation.start(),this._initialized=!0,e(this)}),this._initPromise)}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const i=this._nodes.nodeFrame,n=i.renderId,r=this._currentRenderContext,a=this._currentRenderObjectFunction,l=this._compilationPromises,c=e.isScene===!0?e:pf;s===null&&(s=e);const h=this._renderTarget,u=this._renderContexts.get(s,t,h),d=this._activeMipmapLevel,p=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new al),u.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,h);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,u.clippingContext),s!==e&&s.traverseVisible(function(b){b.isLight&&b.layers.test(t.layers)&&f.pushLight(b)}),f.finish(),h!==null){this._textures.updateRenderTarget(h,d);const b=this._textures.get(h);u.textures=b.textures,u.depthTexture=b.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(c,f,u);const m=f.opaque,y=f.transparent,g=f.transparentDoublePass,_=f.lightsNode;this.opaque===!0&&m.length>0&&this._renderObjects(m,t,c,_),this.transparent===!0&&y.length>0&&this._renderTransparents(y,g,t,c,_),i.renderId=n,this._currentRenderContext=r,this._currentRenderObjectFunction=a,this._compilationPromises=l,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(p)}async renderAsync(e,t){this._initialized===!1&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){e===!0?(this.overrideNodes.modelViewMatrix=hp,this.overrideNodes.modelNormalViewMatrix=up):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===hp&&this.overrideNodes.modelNormalViewMatrix===up}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
|
|
121
|
+
`;return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:s}=this;if(t!==null){let i=s.library.fromMaterial(t);i===null&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),i=new it),i.build(this)}else this.addFlow("compute",e);for(const i of Jd){this.setBuildStage(i),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const n of ep){this.setShaderStage(n);const r=this.flowNodes[n];for(const a of r)i==="generate"?this.flowNode(a):a.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if(t==="float"||t==="int"||t==="uint")return new yE(e);if(t==="vec2"||t==="ivec2"||t==="uvec2")return new xE(e);if(t==="vec3"||t==="ivec3"||t==="uvec3")return new _E(e);if(t==="vec4"||t==="ivec4"||t==="uvec4")return new bE(e);if(t==="color")return new TE(e);if(t==="mat2")return new SE(e);if(t==="mat3")return new vE(e);if(t==="mat4")return new wE(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,s){if(t=this.getVectorType(t),s=this.getVectorType(s),t===s||s===null||this.isReference(s))return e;const i=this.getTypeLength(t),n=this.getTypeLength(s);return i===16&&n===9?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:i===9&&n===4?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||n>4||n===0?e:i===n?`${this.getType(s)}( ${e} )`:i>n?(e=s==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,n)}`,this.format(e,this.getTypeFromLength(n,this.getComponentType(t)),s)):n===4&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:i===2?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(i===1&&n>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${bm} - Node System
|
|
122
|
+
`}*[Symbol.iterator](){}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class sf{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return s===void 0&&(s={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===ue.FRAME){const{frameMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.frameId&&e.updateBefore(this)!==!1&&i.set(s,this.frameId)}else if(t===ue.RENDER){const{renderMap:i}=this._getMaps(this.updateBeforeMap,s);i.get(s)!==this.renderId&&e.updateBefore(this)!==!1&&i.set(s,this.renderId)}else t===ue.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===ue.FRAME){const{frameMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.frameId&&e.updateAfter(this)!==!1&&i.set(s,this.frameId)}else if(t===ue.RENDER){const{renderMap:i}=this._getMaps(this.updateAfterMap,s);i.get(s)!==this.renderId&&e.updateAfter(this)!==!1&&i.set(s,this.renderId)}else t===ue.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===ue.FRAME){const{frameMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.frameId&&e.update(this)!==!1&&i.set(s,this.frameId)}else if(t===ue.RENDER){const{renderMap:i}=this._getMaps(this.updateMap,s);i.get(s)!==this.renderId&&e.update(this)!==!1&&i.set(s,this.renderId)}else t===ue.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class Wu{constructor(e,t,s=null,i="",n=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=n}}Wu.isNodeFunctionInput=!0;class CE extends mn{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:uy(this.light),lightColor:e}}}const Bc=new Ie,ca=new Ie;let zr=null;class EE extends mn{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Q(new N).setGroup(K),this.halfWidth=Q(new N).setGroup(K),this.updateType=ue.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;ca.identity(),Bc.copy(t.matrixWorld),Bc.premultiply(s),ca.extractRotation(Bc),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(ca),this.halfHeight.value.applyMatrix4(ca)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=_e(zr.LTC_FLOAT_1),s=_e(zr.LTC_FLOAT_2)):(t=_e(zr.LTC_HALF_1),s=_e(zr.LTC_HALF_2));const{colorNode:i,light:n}=this,r=hy(n);return{lightColor:i,lightPosition:r,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){zr=e}}class $u extends mn{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Q(0).setGroup(K),this.penumbraCosNode=Q(0).setGroup(K),this.cutoffDistanceNode=Q(0).setGroup(K),this.decayExponentNode=Q(0).setGroup(K),this.colorNode=Q(this.color).setGroup(K)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return Bi(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return s===void 0&&(s=zM(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:n}=this,r=this.getLightVector(e),a=r.normalize(),l=a.dot(uy(n)),c=this.getSpotAttenuation(e,l),h=r.length(),u=my({lightDistance:h,cutoffDistance:s,decayExponent:i});let d=t.mul(c).mul(u),p,f;return n.colorNode?(f=this.getLightCoord(e),p=n.colorNode(f)):n.map&&(f=this.getLightCoord(e),p=_e(n.map,f.xy).onRenderUpdate(()=>n.map)),p&&(d=f.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(p),d)),{lightColor:d,lightDirection:a}}}class AE extends $u{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&s.isTexture===!0){const n=t.acos().mul(1/Math.PI);i=_e(s,H(n,0),0).r}else i=super.getSpotAttenuation(t);return i}}const RE=L(([o,e])=>{const t=o.abs().sub(e);return ni(vt(t,0)).add(fr(vt(t.x,t.y),0))});class NE extends $u{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let s=1;t.map!==null&&(s=t.map.width/t.map.height),t.shadow.aspect=s}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=this.penumbraCosNode,s=this.getLightCoord(e),i=s.xyz.div(s.w),n=RE(i.xy.sub(H(.5)),H(.5)),r=Us(-1,At(1,Sg(t)).sub(1));return Ng(n.mul(-2).mul(r))}}class PE extends mn{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class FE extends mn{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=cy(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Q(new ve).setGroup(K)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=Bu.dot(i).mul(.5).add(.5),a=Ge(s,t,r);e.context.irradiance.addAssign(a)}}class DE extends mn{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let s=0;s<9;s++)t.push(new N);this.lightProbe=Os(t)}update(e){const{light:t}=this;super.update(e);for(let s=0;s<9;s++)this.lightProbe.array[s].copy(t.sh.coefficients[s]).multiplyScalar(t.intensity)}setup(e){const t=jC(Bu,this.lightProbe);e.context.irradiance.addAssign(t)}}const nf=new WeakMap;class OE extends Tr{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const u=s.isTextureNode?s.value:t[s.property];let d=nf.get(u);d===void 0&&(d=yy(u),nf.set(u,d)),s=d}const n=t.useAnisotropy===!0||t.anisotropy>0?nw:et,r=s.context(rf(Xs,n)).mul(oc),a=s.context(BE(Iu)).mul(Math.PI).mul(oc),l=La(r),c=La(a);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);const h=e.context.lightingModel.clearcoatRadiance;if(h){const u=s.context(rf(ol,to)).mul(oc),d=La(u);h.addAssign(d)}}}const rf=(o,e)=>{let t=null;return{getUV:()=>(t===null&&(t=je.negate().reflect(e),t=o.mul(o).mix(t,e).normalize(),t=t.transformDirection(hi)),t),getTextureLevel:()=>o}},BE=o=>({getUV:()=>o,getTextureLevel:()=>B(1)});class ju extends Tr{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=wy(this.envNode)}}class Ey{parseFunction(){console.warn("Abstract function.")}}class qu{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}qu.isNodeFunction=!0;const IE=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,LE=/[a-z_0-9]+/ig,of="#pragma main",UE=o=>{o=o.trim();const e=o.indexOf(of),t=e!==-1?o.slice(e+of.length):o,s=t.match(IE);if(s!==null&&s.length===5){const i=s[4],n=[];let r=null;for(;(r=LE.exec(i))!==null;)n.push(r);const a=[];let l=0;for(;l<n.length;){const f=n[l][0]==="const";f===!0&&l++;let m=n[l][0];m==="in"||m==="out"||m==="inout"?l++:m="";const x=n[l++][0];let g=Number.parseInt(n[l][0]);Number.isNaN(g)===!1?l++:g=null;const _=n[l++][0];a.push(new Wu(x,_,g,m,f))}const c=t.substring(s[0].length),h=s[3]!==void 0?s[3]:"",u=s[2],d=s[1]!==void 0?s[1]:"",p=e!==-1?o.slice(0,e):"";return{type:u,inputs:a,name:h,precision:d,inputsCode:i,blockCode:c,headerCode:p}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class kE extends qu{constructor(e){const{type:t,inputs:s,name:i,precision:n,inputsCode:r,blockCode:a,headerCode:l}=UE(e);super(t,s,i,n),this.inputsCode=r,this.blockCode=a,this.headerCode=l}getCode(e=this.name){let t;const s=this.blockCode;if(s!==""){const{type:i,inputsCode:n,headerCode:r,precision:a}=this;let l=`${i} ${e} ( ${n.trim()} )`;a!==""&&(l=`${a} ${l}`),t=r+l+s}else t="";return t}}class zE extends Ey{parseFunction(e){return new kE(e)}}class Ay extends Nl{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(ne(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(ne(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Se.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,n=e.context.environment;if(n)switch(t.combine){case pl:i.rgb.assign(Ge(i.rgb,i.rgb.mul(n.rgb),ka.mul(ac)));break;case N_:i.rgb.assign(Ge(i.rgb,n.rgb,ka.mul(ac)));break;case P_:i.rgb.addAssign(n.rgb.mul(ka.mul(ac)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const GE=()=>B(.25),VE=L(({dotNH:o})=>kh.mul(B(.5)).add(1).mul(B(1/Math.PI)).mul(o.pow(kh))),HE=L(({lightDirection:o})=>{const e=o.add(je).normalize(),t=et.dot(e).clamp(),s=je.dot(e).clamp(),i=Mo({f0:Yt,f90:1,dotVH:s}),n=GE(),r=VE({dotNH:t});return i.mul(n).mul(r)});class Ry extends Ay{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=et.dot(e).clamp().mul(t);s.directDiffuse.addAssign(n.mul(gr({diffuseColor:Se.rgb}))),this.specular===!0&&s.directSpecular.addAssign(n.mul(HE({lightDirection:e})).mul(ka))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(gr({diffuseColor:Se}))),i.indirectDiffuse.mulAssign(t)}}const Ny=L(o=>{const{dotNV:e,specularColor:t,specularF90:s,roughness:i}=o,n=xy({dotNV:e,roughness:i});return t.mul(n.x).add(s.mul(n.y))}),WE=L(({roughness:o,dotNH:e})=>{const t=o.pow2(),s=B(1).div(t),n=e.pow2().oneMinus().max(.0078125);return B(2).add(s).mul(n.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),$E=L(({dotNV:o,dotNL:e})=>B(1).div(B(4).mul(e.add(o).sub(e.mul(o))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),jE=L(({lightDirection:o})=>{const e=o.add(je).normalize(),t=et.dot(o).clamp(),s=et.dot(je).clamp(),i=et.dot(e).clamp(),n=WE({roughness:Su,dotNH:i}),r=$E({dotNV:s,dotNL:t});return Xn.mul(n).mul(r)}),qE=L(({N:o,V:e,roughness:t})=>{const n=.0078125,r=o.dot(e).saturate(),a=H(t,r.oneMinus().sqrt());return a.assign(a.mul(.984375).add(n)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),YE=L(({f:o})=>{const e=o.length();return vt(e.mul(e).add(o.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),ha=L(({v1:o,v2:e})=>{const t=o.dot(e),s=t.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),r=i.div(n),a=t.greaterThan(0).select(r,vt(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(r));return o.cross(e).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),af=L(({N:o,V:e,P:t,mInv:s,p0:i,p1:n,p2:r,p3:a})=>{const l=n.sub(i).toVar(),c=a.sub(i).toVar(),h=l.cross(c),u=I().toVar();return Ze(h.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(o.mul(e.dot(o))).normalize(),p=o.cross(d).negate(),f=s.mul(Ft(d,p,o).transpose()).toVar(),m=f.mul(i.sub(t)).normalize().toVar(),x=f.mul(n.sub(t)).normalize().toVar(),g=f.mul(r.sub(t)).normalize().toVar(),_=f.mul(a.sub(t)).normalize().toVar(),b=I(0).toVar();b.addAssign(ha({v1:m,v2:x})),b.addAssign(ha({v1:x,v2:g})),b.addAssign(ha({v1:g,v2:_})),b.addAssign(ha({v1:_,v2:m})),u.assign(I(YE({f:b})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),lf=L(([o,e,t,s,i])=>{const n=I(Pg(e.negate(),So(o),Us(1,s))),r=I(ni(i[0].xyz),ni(i[1].xyz),ni(i[2].xyz));return So(n).mul(t.mul(r))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),XE=L(([o,e])=>o.mul(ai(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),ZE=Yg(),KE=Yg(),cf=L(([o,e,t],{material:s})=>{const n=(s.side===Gt?ZE:KE).sample(o),r=ii(Gh.x).mul(XE(e,t));return _M(n,r)}),hf=L(([o,e,t])=>(Ze(t.notEqual(0),()=>{const s=Tg(e).negate().div(t);return bg(s.negate().mul(o))}),I(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),QE=L(([o,e,t,s,i,n,r,a,l,c,h,u,d,p,f])=>{let m,x;if(f){m=ne().toVar(),x=I().toVar();const S=h.sub(1).mul(f.mul(.025)),C=I(h.sub(S),h,h.add(S));Ts({start:0,end:3},({i:w})=>{const R=C.element(w),P=lf(o,e,u,R,a),z=r.add(P),$=c.mul(l.mul(ne(z,1))),q=H($.xy.div($.w)).toVar();q.addAssign(1),q.divAssign(2),q.assign(H(q.x,q.y.oneMinus()));const j=cf(q,t,R);m.element(w).assign(j.element(w)),m.a.addAssign(j.a),x.element(w).assign(s.element(w).mul(hf(ni(P),d,p).element(w)))}),m.a.divAssign(3)}else{const S=lf(o,e,u,h,a),C=r.add(S),w=c.mul(l.mul(ne(C,1))),R=H(w.xy.div(w.w)).toVar();R.addAssign(1),R.divAssign(2),R.assign(H(R.x,R.y.oneMinus())),m=cf(R,t,h),x=s.mul(hf(ni(S),d,p))}const g=x.rgb.mul(m.rgb),_=o.dot(e).clamp(),b=I(Ny({dotNV:_,specularColor:i,specularF90:n,roughness:t})),T=x.r.add(x.g,x.b).div(3);return ne(b.oneMinus().mul(g),m.a.oneMinus().mul(T).oneMinus())}),JE=Ft(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),eA=o=>{const e=o.sqrt();return I(1).add(e).div(I(1).sub(e))},uf=(o,e)=>o.sub(e).div(o.add(e)).pow2(),tA=(o,e)=>{const t=o.mul(2*Math.PI*1e-9),s=I(54856e-17,44201e-17,52481e-17),i=I(1681e3,1795300,2208400),n=I(43278e5,93046e5,66121e5),r=B(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let a=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(n).exp());return a=I(a.x.add(r),a.y,a.z).div(10685e-11),JE.mul(a)},sA=L(({outsideIOR:o,eta2:e,cosTheta1:t,thinFilmThickness:s,baseF0:i})=>{const n=Ge(o,e,Bi(0,.03,s)),a=o.div(n).pow2().mul(t.pow2().oneMinus()).oneMinus();Ze(a.lessThan(0),()=>I(1));const l=a.sqrt(),c=uf(n,o),h=Mo({f0:c,f90:1,dotVH:t}),u=h.oneMinus(),d=n.lessThan(o).select(Math.PI,0),p=B(Math.PI).sub(d),f=eA(i.clamp(0,.9999)),m=uf(f,n.toVec3()),x=Mo({f0:m,f90:1,dotVH:l}),g=I(f.x.lessThan(n).select(Math.PI,0),f.y.lessThan(n).select(Math.PI,0),f.z.lessThan(n).select(Math.PI,0)),_=n.mul(s,l,2),b=I(p).add(g),T=h.mul(x).clamp(1e-5,.9999),S=T.sqrt(),C=u.pow2().mul(x).div(I(1).sub(T)),R=h.add(C).toVar(),P=C.sub(u).toVar();return Ts({start:1,end:2,condition:"<=",name:"m"},({m:z})=>{P.mulAssign(S);const $=tA(B(z).mul(_),B(z).mul(b)).mul(2);R.addAssign(P.mul($))}),R.max(I(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),iA=L(({normal:o,viewDir:e,roughness:t})=>{const s=o.dot(e).saturate(),i=t.pow2(),n=Tt(t.lessThan(.25),B(-339.2).mul(i).add(B(161.4).mul(t)).sub(25.9),B(-8.48).mul(i).add(B(14.3).mul(t)).sub(9.95)),r=Tt(t.lessThan(.25),B(44).mul(i).sub(B(23.7).mul(t)).add(3.26),B(1.97).mul(i).sub(B(3.27).mul(t)).add(.72));return Tt(t.lessThan(.25),0,B(.1).mul(t).sub(.025)).add(n.mul(s).add(r).exp()).mul(1/Math.PI).saturate()}),Ic=I(.04),Lc=B(1);class Py extends Nl{constructor(e=!1,t=!1,s=!1,i=!1,n=!1,r=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=n,this.dispersion=r,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=I().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=I().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=I().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=I().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=I().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=et.dot(je).clamp();this.iridescenceFresnel=sA({outsideIOR:B(1),eta2:pg,cosTheta1:t,thinFilmThickness:fg,baseF0:Yt}),this.iridescenceF0=WC({f:this.iridescenceFresnel,f90:1,dotVH:t})}if(this.transmission===!0){const t=vo,s=Tv.sub(vo).normalize(),i=Iu,n=e.context;n.backdrop=QE(i,s,Xs,Se,Yt,al,t,dn,hi,Ou,Ba,mg,yg,gg,this.dispersion?xg:null),n.backdropAlpha=zh,Se.a.mulAssign(Ge(1,n.backdrop.a,zh))}super.start(e)}computeMultiscattering(e,t,s){const i=et.dot(je).clamp(),n=xy({roughness:Xs,dotNV:i}),a=(this.iridescenceF0?vu.mix(Yt,this.iridescenceF0):Yt).mul(n.x).add(s.mul(n.y)),c=n.x.add(n.y).oneMinus(),h=Yt.add(Yt.oneMinus().mul(.047619)),u=a.mul(h).div(c.mul(h).oneMinus());e.addAssign(a),t.addAssign(u.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const n=et.dot(e).clamp().mul(t);if(this.sheen===!0&&this.sheenSpecularDirect.addAssign(n.mul(jE({lightDirection:e}))),this.clearcoat===!0){const a=to.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(a.mul(Qp({lightDirection:e,f0:Ic,f90:Lc,roughness:ol,normalView:to})))}s.directDiffuse.addAssign(n.mul(gr({diffuseColor:Se.rgb}))),s.directSpecular.addAssign(n.mul(Qp({lightDirection:e,f0:Yt,f90:1,roughness:Xs,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:n,ltc_1:r,ltc_2:a}){const l=t.add(s).sub(i),c=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),d=et,p=je,f=st.toVar(),m=qE({N:d,V:p,roughness:Xs}),x=r.sample(m).toVar(),g=a.sample(m).toVar(),_=Ft(I(x.x,0,x.y),I(0,1,0),I(x.z,0,x.w)).toVar(),b=Yt.mul(g.x).add(Yt.oneMinus().mul(g.y)).toVar();n.directSpecular.addAssign(e.mul(b).mul(af({N:d,V:p,P:f,mInv:_,p0:l,p1:c,p2:h,p3:u}))),n.directDiffuse.addAssign(e.mul(Se).mul(af({N:d,V:p,P:f,mInv:Ft(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:h,p3:u})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(t.mul(gr({diffuseColor:Se})))}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(s.mul(Xn,iA({normal:et,viewDir:je,roughness:Su}))),this.clearcoat===!0){const h=to.dot(je).clamp(),u=Ny({dotNV:h,specularColor:Ic,specularF90:Lc,roughness:ol});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(u))}const n=I().toVar("singleScattering"),r=I().toVar("multiScattering"),a=s.mul(1/Math.PI);this.computeMultiscattering(n,r,al);const l=n.add(r),c=Se.mul(l.r.max(l.g).max(l.b).oneMinus());i.indirectSpecular.addAssign(t.mul(n)),i.indirectSpecular.addAssign(r.mul(a)),i.indirectDiffuse.addAssign(c.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,n=et.dot(je).clamp().add(t),r=Xs.mul(-16).oneMinus().negate().exp2(),a=t.sub(n.pow(r).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(a)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const s=to.dot(je).clamp(),i=Mo({dotVH:s,f0:Ic,f90:Lc}),n=t.mul(Lh.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Lh));t.assign(n)}if(this.sheen===!0){const s=Xn.r.max(Xn.g).max(Xn.b).mul(.157).oneMinus(),i=t.mul(s).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(i)}}}const df=new WeakMap,Ms=[],$i=[];class nA extends Li{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new sf,this.nodeBuilderCache=new Map,this.callHashCache=new vs,this.groupsData=new vs,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===ug.name)return!0;if(s===K.name){const n=this.get(e),r=this.nodeFrame.renderId;return n.renderId!==r?(n.renderId=r,!0):!1}if(s===NT.name){const n=this.get(e),r=this.nodeFrame.frameId;return n.frameId!==r?(n.frameId=r,!0):!1}Ms[0]=t,Ms[1]=e;let i=this.groupsData.get(Ms);return i===void 0&&this.groupsData.set(Ms,i={}),Ms.length=0,i.version!==t.version?(i.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const{nodeBuilderCache:i}=this,n=this.getForRenderCacheKey(e);if(s=i.get(n),s===void 0){const r=this.backend.createNodeBuilder(e.object,this.renderer);r.scene=e.scene,r.material=e.material,r.camera=e.camera,r.context.material=e.material,r.lightsNode=e.lightsNode,r.environmentNode=this.getEnvironmentNode(e.scene),r.fogNode=this.getFogNode(e.scene),r.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&r.enableMultiview(),r.build(),s=this._createNodeBuilderState(r),i.set(n,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(s===void 0){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new XC(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Ms[0]=e,Ms[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Ms)||{};if(i.callId!==s){const n=this.getEnvironmentNode(e),r=this.getFogNode(e);t&&$i.push(t.getCacheKey(!0)),n&&$i.push(n.getCacheKey()),r&&$i.push(r.getCacheKey()),$i.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),$i.push(this.renderer.shadowMap.enabled?1:0),i.callId=s,i.cacheKey=hu($i),this.callHashCache.set(Ms,i),$i.length=0}return Ms.length=0,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==s||i){const n=this.getCacheNode("background",s,()=>{if(s.isCubeTexture===!0||s.mapping===su||s.mapping===iu||s.mapping===gh){if(e.backgroundBlurriness>0||s.mapping===gh)return yy(s);{let r;return s.isCubeTexture===!0?r=wo(s):r=_e(s),wy(r)}}else{if(s.isTexture===!0)return _e(s,or.flipY()).setUpdateMatrix(!0);s.isColor!==!0&&console.error("WebGPUNodes: Unsupported background configuration.",s)}},i);t.backgroundNode=n,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const n=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let r=n.get(t);return(r===void 0||i)&&(r=s(),n.set(t,r)),r}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const i=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const n=Be("color","color",s).setGroup(K),r=Be("density","float",s).setGroup(K);return Ip(n,UM(r))}else if(s.isFog){const n=Be("color","color",s).setGroup(K),r=Be("near","float",s).setGroup(K),a=Be("far","float",s).setGroup(K);return Ip(n,LM(r,a))}else console.error("THREE.Renderer: Unsupported fog configuration.",s)});t.fogNode=i,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const i=this.getCacheNode("environment",s,()=>{if(s.isCubeTexture===!0)return wo(s);if(s.isTexture===!0)return _e(s);console.error("Nodes: Unsupported environment configuration.",s)});t.environmentNode=i,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,n=null){const r=this.nodeFrame;return r.renderer=e,r.scene=t,r.object=s,r.camera=i,r.material=n,r}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return df.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?wM(e,I(or,Tl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):_e(e,or).renderOutput(t.toneMapping,t.currentColorSpace);return df.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const i of s.updateNodes)t.updateNode(i)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const i of s.updateNodes)t.updateNode(i)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new sf,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Uc=new Mi;class cl{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ht,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let n=0;n<i;n++){Uc.copy(e[n]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[s+n],a=Uc.normal;r.x=-a.x,r.y=-a.y,r.z=-a.z,r.w=Uc.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,n=i.length;let r,a;if(this.clipIntersection?(r=this.intersectionPlanes,a=e.intersectionPlanes.length):(r=this.unionPlanes,a=e.unionPlanes.length),r.length!==a+n){r.length=a+n;for(let l=0;l<n;l++)r[a+l]=new ge;s=!0}this.projectPlanes(i,r,a),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new cl(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class rA{constructor(e,t){this.bundleGroup=e,this.camera=t}}const Gr=[];class oA{constructor(){this.bundles=new vs}get(e,t){const s=this.bundles;Gr[0]=e,Gr[1]=t;let i=s.get(Gr);return i===void 0&&(i=new rA(e,t),s.set(Gr,i)),Gr.length=0,i}dispose(){this.bundles=new vs}}class Fy{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(s!==null){t=new s;for(const i in e)t[i]=e[i]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t)){console.warn(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}addClass(e,t,s){if(s.has(t)){console.warn(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}const aA=new dy,Vr=[];class lA extends vs{constructor(){super()}createNode(e=[]){return new dy().setLights(e)}getNode(e,t){if(e.isQuadMesh)return aA;Vr[0]=e,Vr[1]=t;let s=this.get(Vr);return s===void 0&&(s=this.createNode(),this.set(Vr,s)),Vr.length=0,s}}class cA extends Zt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class ua extends dt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const hA={type:"move"};class uA{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ua,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 ua,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ua,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N),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){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}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,s){let i=null,n=null,r=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){r=!0;for(const m of e.hand.values()){const x=t.getJointPose(m,s),g=this._getHandJoint(c,m);x!==null&&(g.matrix.fromArray(x.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=x.radius),g.visible=x!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,f=.005;c.inputState.pinching&&d>p+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(n=t.getPose(e.gripSpace,s),n!==null&&(l.matrix.fromArray(n.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,n.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(n.linearVelocity)):l.hasLinearVelocity=!1,n.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(n.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,s),i===null&&n!==null&&(i=n),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(hA)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=n!==null),c!==null&&(c.visible=r!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new ua;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class io extends fn{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this.hasExternalTextures=!1,this.autoAllocateDepthBuffer=!0}copy(e){return super.copy(e),this.hasExternalTextures=e.hasExternalTextures,this.autoAllocateDepthBuffer=e.autoAllocateDepthBuffer,this}}class Yu extends ui{constructor(e=1,t=1,s=1,i=32,n=1,r=!1,a=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:n,openEnded:r,thetaStart:a,thetaLength:l};const c=this;i=Math.floor(i),n=Math.floor(n);const h=[],u=[],d=[],p=[];let f=0;const m=[],x=s/2;let g=0;_(),r===!1&&(e>0&&b(!0),t>0&&b(!1)),this.setIndex(h),this.setAttribute("position",new Pt(u,3)),this.setAttribute("normal",new Pt(d,3)),this.setAttribute("uv",new Pt(p,2));function _(){const T=new N,S=new N;let C=0;const w=(t-e)/s;for(let R=0;R<=n;R++){const P=[],z=R/n,$=z*(t-e)+e;for(let q=0;q<=i;q++){const j=q/i,X=j*l+a,Z=Math.sin(X),we=Math.cos(X);S.x=$*Z,S.y=-z*s+x,S.z=$*we,u.push(S.x,S.y,S.z),T.set(Z,w,we).normalize(),d.push(T.x,T.y,T.z),p.push(j,1-z),P.push(f++)}m.push(P)}for(let R=0;R<i;R++)for(let P=0;P<n;P++){const z=m[P][R],$=m[P+1][R],q=m[P+1][R+1],j=m[P][R+1];(e>0||P!==0)&&(h.push(z,$,j),C+=3),(t>0||P!==n-1)&&(h.push($,q,j),C+=3)}c.addGroup(g,C,0),g+=C}function b(T){const S=f,C=new he,w=new N;let R=0;const P=T===!0?e:t,z=T===!0?1:-1;for(let q=1;q<=i;q++)u.push(0,x*z,0),d.push(0,z,0),p.push(.5,.5),f++;const $=f;for(let q=0;q<=i;q++){const X=q/i*l+a,Z=Math.cos(X),we=Math.sin(X);w.x=P*we,w.y=x*z,w.z=P*Z,u.push(w.x,w.y,w.z),d.push(0,z,0),C.x=Z*.5+.5,C.y=we*.5*z+.5,p.push(C.x,C.y),f++}for(let q=0;q<i;q++){const j=S+q,X=$+q;T===!0?h.push(X,X+1,j):h.push(X+1,X,j),R+=3}c.addGroup(g,R,T===!0?1:2),g+=R}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Yu(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Xu extends ui{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const n=e/2,r=t/2,a=Math.floor(s),l=Math.floor(i),c=a+1,h=l+1,u=e/a,d=t/l,p=[],f=[],m=[],x=[];for(let g=0;g<h;g++){const _=g*d-r;for(let b=0;b<c;b++){const T=b*u-n;f.push(T,-_,0),m.push(0,0,1),x.push(b/a),x.push(1-g/l)}}for(let g=0;g<l;g++)for(let _=0;_<a;_++){const b=_+c*g,T=_+c*(g+1),S=_+1+c*(g+1),C=_+1+c*g;p.push(b,T,C),p.push(T,S,C)}this.setIndex(p),this.setAttribute("position",new Pt(f,3)),this.setAttribute("normal",new Pt(m,3)),this.setAttribute("uv",new Pt(x,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Xu(e.width,e.height,e.widthSegments,e.heightSegments)}}const pf=new N,ff=new N;class dA extends pn{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Zt,this._cameraL.viewport=new ge,this._cameraR=new Zt,this._cameraR.viewport=new ge,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new cA,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._frameBufferTargets=null,this._createXRLayer=xA.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new he,this._onSessionEvent=mA.bind(this),this._onSessionEnd=gA.bind(this),this._onInputSourcesChange=yA.bind(this),this._onAnimationFrame=_A.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._useLayers=typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(!(this._glProjLayer===null&&this._glBaseLayer===null))return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&console.warn("THREE.XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,n,r,a,l={}){const c=new Xu(e,t),h=new io(n,r,{format:os,type:Nt,depthTexture:new Is(n,r,l.stencil?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?ti:Bs),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h.autoAllocateDepthBuffer=!0;const u=new Ai({color:16777215,side:Qs});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const d=new li(c,u);d.position.copy(s),d.quaternion.copy(i);const p={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:n,pixelheight:r,plane:d,material:u,rendercall:a,renderTarget:h};if(this._layers.push(p),this._session!==null){p.plane.material=new Ai({color:16777215,side:Qs}),p.plane.material.blending=lo,p.plane.material.blendEquation=bs,p.plane.material.blendSrc=vi,p.plane.material.blendDst=vi,p.xrlayer=this._createXRLayer(p);const f=this._session.renderState.layers;f.unshift(p.xrlayer),this._session.updateRenderState({layers:f})}else h.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,n,r,a,l,c={}){const h=new Yu(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new io(r,a,{format:os,type:Nt,depthTexture:new Is(r,a,c.stencil?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?ti:Bs),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u.autoAllocateDepthBuffer=!0;const d=new Ai({color:16777215,side:Gt});d.map=u.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new li(h,d);p.position.copy(i),p.quaternion.copy(n);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:n,pixelwidth:r,pixelheight:a,plane:p,material:d,rendercall:l,renderTarget:u};if(this._layers.push(f),this._session!==null){f.plane.material=new Ai({color:16777215,side:Gt}),f.plane.material.blending=lo,f.plane.material.blendEquation=bs,f.plane.material.blendSrc=vi,f.plane.material.blendDst=vi,f.xrlayer=this._createXRLayer(f);const m=this._session.renderState.layers;m.unshift(f.xrlayer),this._session.updateRenderState({layers:m})}else u.isXRRenderTarget=!1;return p}renderLayers(){const e=new N,t=new xr,s=this._renderer,i=this.isPresenting,n=s.getOutputRenderTarget(),r=s._frameBufferTarget;this.isPresenting=!1;const a=new he;s.getSize(a);const l=s._quad;for(const c of this._layers)if(c.renderTarget.isXRRenderTarget=this._session!==null,c.renderTarget.hasExternalTextures=c.renderTarget.isXRRenderTarget,c.renderTarget.isXRRenderTarget&&this._supportsLayers){c.xrlayer.transform=new XRRigidTransform(c.plane.getWorldPosition(e),c.plane.getWorldQuaternion(t));const h=this._glBinding.getSubImage(c.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(c.renderTarget,h.colorTexture,void 0),s._setXRLayerSize(c.renderTarget.width,c.renderTarget.height),s.setOutputRenderTarget(c.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:u,quad:d}=this._frameBufferTargets.get(c.renderTarget)||{frameBufferTarget:null,quad:null};u?(s._frameBufferTarget=u,s._quad=d):(s._quad=new zu(new it),this._frameBufferTargets.set(c.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),c.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(c.renderTarget),c.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(n),s._frameBufferTarget=r,s._setXRLayerSize(a.x,a.y),s._quad=l,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,n=i.getContextAttributes();if(this._session=e,e!==null){if(s.isWebGPUBackend===!0)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._useLayers===!0){let r=null,a=null,l=null;t.depth&&(l=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,r=t.stencil?ti:Bs,a=t.stencil?Fi:Xe);const c={colorFormat:i.RGBA8,depthFormat:l,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(c.textureType="texture-array",this._useMultiview=!0);const h=new XRWebGLBinding(e,i),u=h.createProjectionLayer(c),d=[u];this._glBinding=h,this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const p=this._useMultiview?2:1,f=new Is(u.textureWidth,u.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,r,p);if(this._xrRenderTarget=new io(u.textureWidth,u.textureHeight,{format:os,type:Nt,colorSpace:t.outputColorSpace,depthTexture:f,stencilBuffer:t.stencil,samples:n.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget.hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const m of this._layers)m.plane.material=new Ai({color:16777215,side:m.type==="cylinder"?Gt:Qs}),m.plane.material.blending=lo,m.plane.material.blendEquation=bs,m.plane.material.blendSrc=vi,m.plane.material.blendDst=vi,m.xrlayer=this._createXRLayer(m),d.unshift(m.xrlayer);e.updateRenderState({layers:d})}else{const r={antialias:t.samples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},a=new XRWebGLLayer(e,i,r);this._glBaseLayer=a,e.updateRenderState({baseLayer:a}),t.setPixelRatio(1),t._setXRLayerSize(a.framebufferWidth,a.framebufferHeight),this._xrRenderTarget=new io(a.framebufferWidth,a.framebufferHeight,{format:os,type:Nt,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:a.ignoreDepthValues===!1,resolveStencilBuffer:a.ignoreDepthValues===!1}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(t===null)return;const s=e.near,i=e.far,n=this._cameraXR,r=this._cameraL,a=this._cameraR;n.near=a.near=r.near=s,n.far=a.far=r.far=i,n.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==n.near||this._currentDepthFar!==n.far)&&(t.updateRenderState({depthNear:n.near,depthFar:n.far}),this._currentDepthNear=n.near,this._currentDepthFar=n.far),r.layers.mask=e.layers.mask|2,a.layers.mask=e.layers.mask|4,n.layers.mask=r.layers.mask|a.layers.mask;const l=e.parent,c=n.cameras;mf(n,l);for(let h=0;h<c.length;h++)mf(c[h],l);c.length===2?pA(n,r,a):n.projectionMatrix.copy(r.projectionMatrix),fA(e,n,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new uA,this._controllers[e]=t),t}}function pA(o,e,t){pf.setFromMatrixPosition(e.matrixWorld),ff.setFromMatrixPosition(t.matrixWorld);const s=pf.distanceTo(ff),i=e.projectionMatrix.elements,n=t.projectionMatrix.elements,r=i[14]/(i[10]-1),a=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],h=(i[8]-1)/i[0],u=(n[8]+1)/n[0],d=r*h,p=r*u,f=s/(-h+u),m=f*-h;if(e.matrixWorld.decompose(o.position,o.quaternion,o.scale),o.translateX(m),o.translateZ(f),o.matrixWorld.compose(o.position,o.quaternion,o.scale),o.matrixWorldInverse.copy(o.matrixWorld).invert(),i[10]===-1)o.projectionMatrix.copy(e.projectionMatrix),o.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const x=r+f,g=a+f,_=d-m,b=p+(s-m),T=l*a/g*x,S=c*a/g*x;o.projectionMatrix.makePerspective(_,b,T,S,x,g),o.projectionMatrixInverse.copy(o.projectionMatrix).invert()}}function mf(o,e){e===null?o.matrixWorld.copy(o.matrix):o.matrixWorld.multiplyMatrices(e.matrixWorld,o.matrix),o.matrixWorldInverse.copy(o.matrixWorld).invert()}function fA(o,e,t){t===null?o.matrix.copy(e.matrixWorld):(o.matrix.copy(t.matrixWorld),o.matrix.invert(),o.matrix.multiply(e.matrixWorld)),o.matrix.decompose(o.position,o.quaternion,o.scale),o.updateMatrixWorld(!0),o.projectionMatrix.copy(e.projectionMatrix),o.projectionMatrixInverse.copy(e.projectionMatrixInverse),o.isPerspectiveCamera&&(o.fov=cr*2*Math.atan(1/o.projectionMatrix.elements[5]),o.zoom=1)}function mA(o){const e=this._controllerInputSources.indexOf(o.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const s=this.getReferenceSpace();t.update(o.inputSource,o.frame,s),t.dispatchEvent({type:o.type,data:o.inputSource})}}function gA(){const o=this._session,e=this._renderer;o.removeEventListener("select",this._onSessionEvent),o.removeEventListener("selectstart",this._onSessionEvent),o.removeEventListener("selectend",this._onSessionEvent),o.removeEventListener("squeeze",this._onSessionEvent),o.removeEventListener("squeezestart",this._onSessionEvent),o.removeEventListener("squeezeend",this._onSessionEvent),o.removeEventListener("end",this._onSessionEnd),o.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const s=this._controllerInputSources[t];s!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(s))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._session=null,this._xrRenderTarget=null,this._supportsLayers===!0)for(const t of this._layers)t.renderTarget=new io(t.pixelwidth,t.pixelheight,{format:os,type:Nt,depthTexture:new Is(t.pixelwidth,t.pixelheight,t.stencilBuffer?Fi:Xe,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?ti:Bs),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function yA(o){const e=this._controllers,t=this._controllerInputSources;for(let s=0;s<o.removed.length;s++){const i=o.removed[s],n=t.indexOf(i);n>=0&&(t[n]=null,e[n].disconnect(i))}for(let s=0;s<o.added.length;s++){const i=o.added[s];let n=t.indexOf(i);if(n===-1){for(let a=0;a<e.length;a++)if(a>=t.length){t.push(i),n=a;break}else if(t[a]===null){t[a]=i,n=a;break}if(n===-1)break}const r=e[n];r&&r.connect(i)}}function xA(o){return o.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(o.translation,o.quaternion),width:o.width/2,height:o.height/2,space:this._referenceSpace,viewPixelWidth:o.pixelwidth,viewPixelHeight:o.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(o.translation,o.quaternion),radius:o.radius,centralAngle:o.centralAngle,aspectRatio:o.aspectRatio,space:this._referenceSpace,viewPixelWidth:o.pixelwidth,viewPixelHeight:o.pixelheight,clearOnAccess:!1})}function _A(o,e){if(e===void 0)return;const t=this._cameraXR,s=this._renderer,i=s.backend,n=this._glBaseLayer,r=this.getReferenceSpace(),a=e.getViewerPose(r);if(this._xrFrame=e,a!==null){const l=a.views;this._glBaseLayer!==null&&i.setXRTarget(n.framebuffer);let c=!1;l.length!==t.cameras.length&&(t.cameras.length=0,c=!0);for(let h=0;h<l.length;h++){const u=l[h];let d;if(this._useLayers===!0){const f=this._glBinding.getViewSubImage(this._glProjLayer,u);d=f.viewport,h===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,f.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:f.depthStencilTexture)}else d=n.getViewport(u);let p=this._cameras[h];p===void 0&&(p=new Zt,p.layers.enable(h),p.viewport=new ge,this._cameras[h]=p),p.matrix.fromArray(u.transform.matrix),p.matrix.decompose(p.position,p.quaternion,p.scale),p.projectionMatrix.fromArray(u.projectionMatrix),p.projectionMatrixInverse.copy(p.projectionMatrix).invert(),p.viewport.set(d.x,d.y,d.width,d.height),h===0&&(t.matrix.copy(p.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),c===!0&&t.cameras.push(p)}s.setOutputRenderTarget(this._xrRenderTarget)}for(let l=0;l<this._controllers.length;l++){const c=this._controllerInputSources[l],h=this._controllers[l];c!==null&&h!==void 0&&h.update(c,e,r)}this._currentAnimationLoop&&this._currentAnimationLoop(o,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}const ji=new bl,da=new N;class Zu{constructor(e=new Mi,t=new Mi,s=new Mi,i=new Mi,n=new Mi,r=new Mi){this.planes=[e,t,s,i,n,r]}set(e,t,s,i,n,r){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(n),a[5].copy(r),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=Ut){const s=this.planes,i=e.elements,n=i[0],r=i[1],a=i[2],l=i[3],c=i[4],h=i[5],u=i[6],d=i[7],p=i[8],f=i[9],m=i[10],x=i[11],g=i[12],_=i[13],b=i[14],T=i[15];if(s[0].setComponents(l-n,d-c,x-p,T-g).normalize(),s[1].setComponents(l+n,d+c,x+p,T+g).normalize(),s[2].setComponents(l+r,d+h,x+f,T+_).normalize(),s[3].setComponents(l-r,d-h,x-f,T-_).normalize(),s[4].setComponents(l-a,d-u,x-m,T-b).normalize(),t===Ut)s[5].setComponents(l+a,d+u,x+m,T+b).normalize();else if(t===Oi)s[5].setComponents(a,u,m,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ji.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ji.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ji)}intersectsSprite(e){return ji.center.set(0,0,0),ji.radius=.7071067811865476,ji.applyMatrix4(e.matrixWorld),this.intersectsSphere(ji)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let n=0;n<6;n++)if(t[n].distanceToPoint(s)<i)return!1;return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(da.x=i.normal.x>0?e.max.x:e.min.x,da.y=i.normal.y>0?e.max.y:e.min.y,da.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(da)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const Cs=new Ie,Es=new Zu;class Ku{constructor(){this.coordinateSystem=Ut}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Cs.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Es.setFromProjectionMatrix(Cs,this.coordinateSystem),Es.containsPoint(e))return!0}return!1}clone(){return new Ku}}const gf=new uu,pa=new he,kc=new ge,zc=new Zu,Gc=new Ku,fa=new Ie,xi=new ge;class bA{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:n=!0,stencil:r=!1,antialias:a=!1,samples:l=0,getFallback:c=null,colorBufferType:h=rs,multiview:u=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=l||a===!0?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Xt,this.toneMapping=er,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=r,this.info=new vb,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new Fy,this.lighting=new lA,this._getFallback=c,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ge(0,0,this._width,this._height),this._scissor=new ge(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new zu(new it),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const d=this.alpha===!0?0:1;this._clearColor=new fu(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._colorBufferType=h,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:E_},this.xr=new dA(this,u),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,f,m)=>{await this.compileAsync(p,f);const x=this._renderLists.get(p,f),g=this._renderContexts.get(p,f,this._renderTarget),_=p.overrideMaterial||m.material,b=this._objects.get(m,_,p,f,x.lightsNode,g,g.clippingContext),{fragmentShader:T,vertexShader:S}=b.getNodeBuilderState();return{fragmentShader:T,vertexShader:S}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=s=this._getFallback(i),await s.init(this)}catch(n){t(n);return}else{t(i);return}}this._nodes=new nA(this,s),this._animation=new S_(this._nodes,this.info),this._attributes=new _b(s),this._background=new qC(this,this._nodes),this._geometries=new Sb(this._attributes,this.info),this._textures=new jb(this,s,this.info),this._pipelines=new Eb(s,this._nodes),this._bindings=new Ab(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new gb(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Pb(this.lighting),this._bundles=new oA,this._renderContexts=new Gb,this._animation.start(),this._initialized=!0,e(this)}),this._initPromise)}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const i=this._nodes.nodeFrame,n=i.renderId,r=this._currentRenderContext,a=this._currentRenderObjectFunction,l=this._compilationPromises,c=e.isScene===!0?e:gf;s===null&&(s=e);const h=this._renderTarget,u=this._renderContexts.get(s,t,h),d=this._activeMipmapLevel,p=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new cl),u.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,h);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,u.clippingContext),s!==e&&s.traverseVisible(function(b){b.isLight&&b.layers.test(t.layers)&&f.pushLight(b)}),f.finish(),h!==null){this._textures.updateRenderTarget(h,d);const b=this._textures.get(h);u.textures=b.textures,u.depthTexture=b.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(c,f,u);const m=f.opaque,x=f.transparent,g=f.transparentDoublePass,_=f.lightsNode;this.opaque===!0&&m.length>0&&this._renderObjects(m,t,c,_),this.transparent===!0&&x.length>0&&this._renderTransparents(x,g,t,c,_),i.renderId=n,this._currentRenderContext=r,this._currentRenderObjectFunction=a,this._compilationPromises=l,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(p)}async renderAsync(e,t){this._initialized===!1&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){e===!0?(this.overrideNodes.modelViewMatrix=pp,this.overrideNodes.modelNormalViewMatrix=fp):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===pp&&this.overrideNodes.modelNormalViewMatrix===fp}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
|
|
123
123
|
|
|
124
124
|
Message: ${e.message}`;e.reason&&(t+=`
|
|
125
|
-
Reason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:n,renderList:r}=e,a=this._currentRenderContext,l=this._bundles.get(i,n),c=this.backend.get(l);c.renderContexts===void 0&&(c.renderContexts=new Set);const h=i.version!==c.version,u=c.renderContexts.has(a)===!1||h;if(c.renderContexts.add(a),u){this.backend.beginBundle(a),(c.renderObjects===void 0||h)&&(c.renderObjects=[]),this._currentRenderBundle=l;const{transparentDoublePass:d,transparent:p,opaque:f}=r;this.opaque===!0&&f.length>0&&this._renderObjects(f,n,t,s),this.transparent===!0&&p.length>0&&this._renderTransparents(p,d,n,t,s),this._currentRenderBundle=null,this.backend.finishBundle(a,l),c.version=i.version}else{const{renderObjects:d}=c;for(let p=0,f=d.length;p<f;p++){const m=d[p];this._nodes.needsRefresh(m)&&(this._nodes.updateBefore(m),this._nodes.updateForRender(m),this._bindings.updateForRender(m),this._nodes.updateAfter(m))}}this.backend.addBundle(a,l)}render(e,t){if(this._initialized===!1)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(e!==Kn===!1&&t!==Jn===!1)return null;const{width:n,height:r}=this.getDrawingBufferSize(da),{depth:a,stencil:l}=this;let c=this._frameBufferTarget;c===null&&(c=new fn(n,r,{depthBuffer:a,stencilBuffer:l,type:this._colorBufferType,format:os,colorSpace:Jn,generateMipmaps:!1,minFilter:Kt,magFilter:Kt,samples:this.samples}),c.isPostProcessingRenderTarget=!0,this._frameBufferTarget=c);const h=this.getOutputRenderTarget();return c.depthBuffer=a,c.stencilBuffer=l,h!==null?c.setSize(h.width,h.height,h.depth):c.setSize(n,r,1),c.viewport.copy(this._viewport),c.scissor.copy(this._scissor),c.viewport.multiplyScalar(this._pixelRatio),c.scissor.multiplyScalar(this._pixelRatio),c.scissorTest=this._scissorTest,c.multiview=h!==null?h.multiview:!1,c.resolveDepthBuffer=h!==null?h.resolveDepthBuffer:!0,c.autoAllocateDepthBuffer=h!==null?h.autoAllocateDepthBuffer:!1,c}_renderScene(e,t,s=!0){if(this._isDeviceLost===!0)return;const i=s?this._getFrameBufferTarget():null,n=this._nodes.nodeFrame,r=n.renderId,a=this._currentRenderContext,l=this._currentRenderObjectFunction,c=e.isScene===!0?e:pf,h=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,d=this._activeMipmapLevel;let p;i!==null?(p=i,this.setRenderTarget(p)):p=h;const f=this._renderContexts.get(e,t,p);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,n.renderId=this.info.calls;const m=this.coordinateSystem,y=this.xr;if(t.coordinateSystem!==m&&y.isPresenting===!1&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const j of t.cameras)j.coordinateSystem=m,j.updateProjectionMatrix();e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),y.enabled===!0&&y.isPresenting===!0&&(y.cameraAutoUpdate===!0&&y.updateCamera(t),t=y.getCamera());let g=this._viewport,_=this._scissor,b=this._pixelRatio;p!==null&&(g=p.viewport,_=p.scissor,b=1),this.getDrawingBufferSize(da),Ic.set(0,0,da.width,da.height);const T=g.minDepth===void 0?0:g.minDepth,S=g.maxDepth===void 0?1:g.maxDepth;f.viewportValue.copy(g).multiplyScalar(b).floor(),f.viewportValue.width>>=d,f.viewportValue.height>>=d,f.viewportValue.minDepth=T,f.viewportValue.maxDepth=S,f.viewport=f.viewportValue.equals(Ic)===!1,f.scissorValue.copy(_).multiplyScalar(b).floor(),f.scissor=this._scissorTest&&f.scissorValue.equals(Ic)===!1,f.scissorValue.width>>=d,f.scissorValue.height>>=d,f.clippingContext||(f.clippingContext=new al),f.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,p);const C=t.isArrayCamera?Uc:Lc;t.isArrayCamera||(pa.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),C.setFromProjectionMatrix(pa,m));const w=this._renderLists.get(e,t);if(w.begin(),this._projectObject(e,t,0,w,f.clippingContext),w.finish(),this.sortObjects===!0&&w.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,d);const j=this._textures.get(p);f.textures=j.textures,f.depthTexture=j.depthTexture,f.width=j.width,f.height=j.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=this.domElement.width,f.height=this.domElement.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=d,f.height>>=d,f.activeCubeFace=u,f.activeMipmapLevel=d,f.occlusionQueryCount=w.occlusionQueryCount,this._background.update(c,w,f),f.camera=t,this.backend.beginRender(f);const{bundles:R,lightsNode:P,transparentDoublePass:z,transparent:$,opaque:q}=w;return R.length>0&&this._renderBundles(R,c,P),this.opaque===!0&&q.length>0&&this._renderObjects(q,t,c,P),this.transparent===!0&&$.length>0&&this._renderTransparents($,z,t,c,P),this.backend.finishRender(f),n.renderId=r,this._currentRenderContext=a,this._currentRenderObjectFunction=l,i!==null&&(this.setRenderTarget(h,u,d),this._renderOutput(p)),c.onAfterRender(this,e,t,p),f}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),s===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const n=this._scissor;e.isVector4?n.copy(e):n.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,n=0,r=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=n,a.maxDepth=r}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(this._initialized===!1)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,s);const i=this._renderTarget||this._getFrameBufferTarget();let n=null;if(i!==null){this._textures.updateRenderTarget(i);const r=this._textures.get(i);n=this._renderContexts.getForClear(i),n.textures=r.textures,n.depthTexture=r.depthTexture,n.width=r.width,n.height=r.height,n.renderTarget=i,n.depth=i.depthBuffer,n.stencil=i.stencilBuffer,n.clearColorValue=this.backend.getClearColor(),n.activeCubeFace=this.getActiveCubeFace(),n.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,n),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){this._initialized===!1&&await this.init(),this.clear(e,t,s)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:Kn}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Jn}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this._frameBufferTarget!==null&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&e.dispose()}),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,n=this._pipelines,r=this._bindings,a=this._nodes,l=Array.isArray(e)?e:[e];if(l[0]===void 0||l[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const c of l){if(n.has(c)===!1){const d=()=>{c.removeEventListener("dispose",d),n.delete(c),r.delete(c),a.delete(c)};c.addEventListener("dispose",d);const p=c.onInitFunction;p!==null&&p.call(c,{renderer:this})}a.updateForCompute(c),r.updateForCompute(c);const h=r.getForCompute(c),u=n.getForCompute(c,h);i.compute(e,c,h,u)}i.finishCompute(e),t.renderId=s}async computeAsync(e){this._initialized===!1&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return this._initialized===!1&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return this._initialized===!1?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){this._initialized===!1&&await this.init(),this._textures.updateTexture(e)}initTexture(e){this._initialized===!1&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=xi.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=xi.copy(t).floor();else{console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=xi.set(0,0,e.image.width,e.image.height);let s=this._currentRenderContext,i;s!==null?i=s.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),s=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,n,r)}async readRenderTargetPixelsAsync(e,t,s,i,n,r=0,a=0){return this.backend.copyTextureToBuffer(e.textures[r],t,s,i,n,a)}_projectObject(e,t,s,i,n){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(n=n.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const l=t.isArrayCamera?Uc:Lc;if(!e.frustumCulled||l.intersectsSprite(e,t)){this.sortObjects===!0&&xi.setFromMatrixPosition(e.matrixWorld).applyMatrix4(pa);const{geometry:c,material:h}=e;h.visible&&i.push(e,c,h,s,xi.z,null,n)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const l=t.isArrayCamera?Uc:Lc;if(!e.frustumCulled||l.intersectsObject(e,t)){const{geometry:c,material:h}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),xi.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(pa)),Array.isArray(h)){const u=c.groups;for(let d=0,p=u.length;d<p;d++){const f=u[d],m=h[f.materialIndex];m&&m.visible&&i.push(e,c,m,s,xi.z,f,n)}}else h.visible&&i.push(e,c,h,s,xi.z,null,n)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const l=i;i=this._renderLists.get(e,t),i.begin(),l.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const a=e.children;for(let l=0,c=a.length;l<c;l++)this._projectObject(a[l],t,s,i,n)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,n){if(t.length>0){for(const{material:r}of t)r.side=Vt;this._renderObjects(t,s,i,n,"backSide");for(const{material:r}of t)r.side=Ks;this._renderObjects(e,s,i,n);for(const{material:r}of t)r.side=Qn}else this._renderObjects(e,s,i,n)}_renderObjects(e,t,s,i,n=null){for(let r=0,a=e.length;r<a;r++){const{object:l,geometry:c,material:h,group:u,clippingContext:d}=e[r];this._currentRenderObjectFunction(l,s,t,c,h,u,i,d,n)}}renderObject(e,t,s,i,n,r,a,l=null,c=null){let h,u,d;if(e.onBeforeRender(this,t,s,i,n,r),n.allowOverride===!0&&t.overrideMaterial!==null){const p=t.overrideMaterial;n.positionNode&&n.positionNode.isNode&&(h=p.positionNode,p.positionNode=n.positionNode),p.alphaTest=n.alphaTest,p.alphaMap=n.alphaMap,p.transparent=n.transparent||n.transmission>0,p.isShadowPassMaterial&&(p.side=n.shadowSide===null?n.side:n.shadowSide,n.depthNode&&n.depthNode.isNode&&(d=p.depthNode,p.depthNode=n.depthNode),n.castShadowNode&&n.castShadowNode.isNode&&(u=p.colorNode,p.colorNode=n.castShadowNode),n.castShadowPositionNode&&n.castShadowPositionNode.isNode&&(h=p.positionNode,p.positionNode=n.castShadowPositionNode)),n=p}n.transparent===!0&&n.side===Qn&&n.forceSinglePass===!1?(n.side=Vt,this._handleObjectFunction(e,n,t,s,a,r,l,"backSide"),n.side=Ks,this._handleObjectFunction(e,n,t,s,a,r,l,c),n.side=Qn):this._handleObjectFunction(e,n,t,s,a,r,l,c),h!==void 0&&(t.overrideMaterial.positionNode=h),d!==void 0&&(t.overrideMaterial.depthNode=d),u!==void 0&&(t.overrideMaterial.colorNode=u),e.onAfterRender(this,t,s,i,n,r)}_renderObjectDirect(e,t,s,i,n,r,a,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=r;const h=this._nodes.needsRefresh(c);h&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup),this.backend.draw(c,this.info),h&&this._nodes.updateAfter(c)}_createObjectPipeline(e,t,s,i,n,r,a,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=r,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}get compile(){return this.compileAsync}}class Zu{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}function QE(o){return o+(Ci-o%Ci)%Ci}class Ry extends Zu{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return QE(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class Ny extends Ry{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let KE=0;class Py extends Ny{constructor(e,t){super("UniformBuffer_"+KE++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class JE extends Ny{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const n=this.uniforms[s],r=n.boundary,a=n.itemSize*e,l=t%Ci,c=l%r,h=l+c;t+=c,h!==0&&Ci-h<a&&(t+=Ci-h),n.offset=t/e,t+=a}return Math.ceil(t/Ci)*Ci}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);console.error("THREE.WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n]!==i){const a=this._getBufferForType(r);a[n]=s[n]=i,t=!0}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,t=!0}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,a[n+2]=s[n+2]=i.z,t=!0}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z||s[n+4]!==i.w){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,a[n+2]=s[n+2]=i.z,a[n+3]=s[n+3]=i.w,t=!0}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset;if(s[n+0]!==i.r||s[n+1]!==i.g||s[n+2]!==i.b){const r=this.buffer;r[n+0]=s[n+0]=i.r,r[n+1]=s[n+1]=i.g,r[n+2]=s[n+2]=i.b,t=!0}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;if(s[n+0]!==i[0]||s[n+1]!==i[1]||s[n+2]!==i[2]||s[n+4]!==i[3]||s[n+5]!==i[4]||s[n+6]!==i[5]||s[n+8]!==i[6]||s[n+9]!==i[7]||s[n+10]!==i[8]){const r=this.buffer;r[n+0]=s[n+0]=i[0],r[n+1]=s[n+1]=i[1],r[n+2]=s[n+2]=i[2],r[n+4]=s[n+4]=i[3],r[n+5]=s[n+5]=i[4],r[n+6]=s[n+6]=i[5],r[n+8]=s[n+8]=i[6],r[n+9]=s[n+9]=i[7],r[n+10]=s[n+10]=i[8],t=!0}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;return tA(s,i,n)===!1&&(this.buffer.set(i,n),eA(s,i,n),t=!0),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function eA(o,e,t){for(let s=0,i=e.length;s<i;s++)o[t+s]=e[s]}function tA(o,e,t){for(let s=0,i=e.length;s<i;s++)if(o[t+s]!==e[s])return!1;return!0}let sA=0;class Fy extends JE{constructor(e,t){super(e),this.id=sA++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let iA=0;class nA extends Zu{constructor(e,t){super(e),this.id=iA++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}}class Al extends nA{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Dy extends Al{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Oy extends Al{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}class rA extends St{constructor(e=null,t=1,s=1,i,n,r,a,l,c=ut,h=ut,u,d){super(null,r,a,l,c,h,i,n,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const oA={textureDimensions:"textureSize",equals:"equal"},aA={low:"lowp",medium:"mediump",high:"highp"},ff={swizzleAssign:!0,storageBuffer:!1},mf={perspective:"smooth",linear:"noperspective"},gf={centroid:"centroid","flat first":"flat","flat either":"flat"},yf=`
|
|
125
|
+
Reason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:n,renderList:r}=e,a=this._currentRenderContext,l=this._bundles.get(i,n),c=this.backend.get(l);c.renderContexts===void 0&&(c.renderContexts=new Set);const h=i.version!==c.version,u=c.renderContexts.has(a)===!1||h;if(c.renderContexts.add(a),u){this.backend.beginBundle(a),(c.renderObjects===void 0||h)&&(c.renderObjects=[]),this._currentRenderBundle=l;const{transparentDoublePass:d,transparent:p,opaque:f}=r;this.opaque===!0&&f.length>0&&this._renderObjects(f,n,t,s),this.transparent===!0&&p.length>0&&this._renderTransparents(p,d,n,t,s),this._currentRenderBundle=null,this.backend.finishBundle(a,l),c.version=i.version}else{const{renderObjects:d}=c;for(let p=0,f=d.length;p<f;p++){const m=d[p];this._nodes.needsRefresh(m)&&(this._nodes.updateBefore(m),this._nodes.updateForRender(m),this._bindings.updateForRender(m),this._nodes.updateAfter(m))}}this.backend.addBundle(a,l)}render(e,t){if(this._initialized===!1)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(e!==er===!1&&t!==tr===!1)return null;const{width:n,height:r}=this.getDrawingBufferSize(pa),{depth:a,stencil:l}=this;let c=this._frameBufferTarget;c===null&&(c=new fn(n,r,{depthBuffer:a,stencilBuffer:l,type:this._colorBufferType,format:os,colorSpace:tr,generateMipmaps:!1,minFilter:Qt,magFilter:Qt,samples:this.samples}),c.isPostProcessingRenderTarget=!0,this._frameBufferTarget=c);const h=this.getOutputRenderTarget();return c.depthBuffer=a,c.stencilBuffer=l,h!==null?c.setSize(h.width,h.height,h.depth):c.setSize(n,r,1),c.viewport.copy(this._viewport),c.scissor.copy(this._scissor),c.viewport.multiplyScalar(this._pixelRatio),c.scissor.multiplyScalar(this._pixelRatio),c.scissorTest=this._scissorTest,c.multiview=h!==null?h.multiview:!1,c.resolveDepthBuffer=h!==null?h.resolveDepthBuffer:!0,c.autoAllocateDepthBuffer=h!==null?h.autoAllocateDepthBuffer:!1,c}_renderScene(e,t,s=!0){if(this._isDeviceLost===!0)return;const i=s?this._getFrameBufferTarget():null,n=this._nodes.nodeFrame,r=n.renderId,a=this._currentRenderContext,l=this._currentRenderObjectFunction,c=e.isScene===!0?e:gf,h=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,d=this._activeMipmapLevel;let p;i!==null?(p=i,this.setRenderTarget(p)):p=h;const f=this._renderContexts.get(e,t,p);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,n.renderId=this.info.calls;const m=this.coordinateSystem,x=this.xr;if(t.coordinateSystem!==m&&x.isPresenting===!1&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const j of t.cameras)j.coordinateSystem=m,j.updateProjectionMatrix();e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),x.enabled===!0&&x.isPresenting===!0&&(x.cameraAutoUpdate===!0&&x.updateCamera(t),t=x.getCamera());let g=this._viewport,_=this._scissor,b=this._pixelRatio;p!==null&&(g=p.viewport,_=p.scissor,b=1),this.getDrawingBufferSize(pa),kc.set(0,0,pa.width,pa.height);const T=g.minDepth===void 0?0:g.minDepth,S=g.maxDepth===void 0?1:g.maxDepth;f.viewportValue.copy(g).multiplyScalar(b).floor(),f.viewportValue.width>>=d,f.viewportValue.height>>=d,f.viewportValue.minDepth=T,f.viewportValue.maxDepth=S,f.viewport=f.viewportValue.equals(kc)===!1,f.scissorValue.copy(_).multiplyScalar(b).floor(),f.scissor=this._scissorTest&&f.scissorValue.equals(kc)===!1,f.scissorValue.width>>=d,f.scissorValue.height>>=d,f.clippingContext||(f.clippingContext=new cl),f.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,p);const C=t.isArrayCamera?Gc:zc;t.isArrayCamera||(fa.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),C.setFromProjectionMatrix(fa,m));const w=this._renderLists.get(e,t);if(w.begin(),this._projectObject(e,t,0,w,f.clippingContext),w.finish(),this.sortObjects===!0&&w.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,d);const j=this._textures.get(p);f.textures=j.textures,f.depthTexture=j.depthTexture,f.width=j.width,f.height=j.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=this.domElement.width,f.height=this.domElement.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=d,f.height>>=d,f.activeCubeFace=u,f.activeMipmapLevel=d,f.occlusionQueryCount=w.occlusionQueryCount,this._background.update(c,w,f),f.camera=t,this.backend.beginRender(f);const{bundles:R,lightsNode:P,transparentDoublePass:z,transparent:$,opaque:q}=w;return R.length>0&&this._renderBundles(R,c,P),this.opaque===!0&&q.length>0&&this._renderObjects(q,t,c,P),this.transparent===!0&&$.length>0&&this._renderTransparents($,z,t,c,P),this.backend.finishRender(f),n.renderId=r,this._currentRenderContext=a,this._currentRenderObjectFunction=l,i!==null&&(this.setRenderTarget(h,u,d),this._renderOutput(p)),c.onAfterRender(this,e,t,p),f}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),s===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const n=this._scissor;e.isVector4?n.copy(e):n.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,n=0,r=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=n,a.maxDepth=r}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(this._initialized===!1)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,s);const i=this._renderTarget||this._getFrameBufferTarget();let n=null;if(i!==null){this._textures.updateRenderTarget(i);const r=this._textures.get(i);n=this._renderContexts.getForClear(i),n.textures=r.textures,n.depthTexture=r.depthTexture,n.width=r.width,n.height=r.height,n.renderTarget=i,n.depth=i.depthBuffer,n.stencil=i.stencilBuffer,n.clearColorValue=this.backend.getClearColor(),n.activeCubeFace=this.getActiveCubeFace(),n.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,n),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){this._initialized===!1&&await this.init(),this.clear(e,t,s)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:er}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:tr}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),this._frameBufferTarget!==null&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&e.dispose()}),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,n=this._pipelines,r=this._bindings,a=this._nodes,l=Array.isArray(e)?e:[e];if(l[0]===void 0||l[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const c of l){if(n.has(c)===!1){const d=()=>{c.removeEventListener("dispose",d),n.delete(c),r.delete(c),a.delete(c)};c.addEventListener("dispose",d);const p=c.onInitFunction;p!==null&&p.call(c,{renderer:this})}a.updateForCompute(c),r.updateForCompute(c);const h=r.getForCompute(c),u=n.getForCompute(c,h);i.compute(e,c,h,u)}i.finishCompute(e),t.renderId=s}async computeAsync(e){this._initialized===!1&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return this._initialized===!1&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return this._initialized===!1?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){this._initialized===!1&&await this.init(),this._textures.updateTexture(e)}initTexture(e){this._initialized===!1&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=xi.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=xi.copy(t).floor();else{console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=xi.set(0,0,e.image.width,e.image.height);let s=this._currentRenderContext,i;s!==null?i=s.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),s=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,n,r)}async readRenderTargetPixelsAsync(e,t,s,i,n,r=0,a=0){return this.backend.copyTextureToBuffer(e.textures[r],t,s,i,n,a)}_projectObject(e,t,s,i,n){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(n=n.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const l=t.isArrayCamera?Gc:zc;if(!e.frustumCulled||l.intersectsSprite(e,t)){this.sortObjects===!0&&xi.setFromMatrixPosition(e.matrixWorld).applyMatrix4(fa);const{geometry:c,material:h}=e;h.visible&&i.push(e,c,h,s,xi.z,null,n)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const l=t.isArrayCamera?Gc:zc;if(!e.frustumCulled||l.intersectsObject(e,t)){const{geometry:c,material:h}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),xi.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(fa)),Array.isArray(h)){const u=c.groups;for(let d=0,p=u.length;d<p;d++){const f=u[d],m=h[f.materialIndex];m&&m.visible&&i.push(e,c,m,s,xi.z,f,n)}}else h.visible&&i.push(e,c,h,s,xi.z,null,n)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const l=i;i=this._renderLists.get(e,t),i.begin(),l.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const a=e.children;for(let l=0,c=a.length;l<c;l++)this._projectObject(a[l],t,s,i,n)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,n){if(t.length>0){for(const{material:r}of t)r.side=Gt;this._renderObjects(t,s,i,n,"backSide");for(const{material:r}of t)r.side=Qs;this._renderObjects(e,s,i,n);for(const{material:r}of t)r.side=Jn}else this._renderObjects(e,s,i,n)}_renderObjects(e,t,s,i,n=null){for(let r=0,a=e.length;r<a;r++){const{object:l,geometry:c,material:h,group:u,clippingContext:d}=e[r];this._currentRenderObjectFunction(l,s,t,c,h,u,i,d,n)}}renderObject(e,t,s,i,n,r,a,l=null,c=null){let h,u,d;if(e.onBeforeRender(this,t,s,i,n,r),n.allowOverride===!0&&t.overrideMaterial!==null){const p=t.overrideMaterial;n.positionNode&&n.positionNode.isNode&&(h=p.positionNode,p.positionNode=n.positionNode),p.alphaTest=n.alphaTest,p.alphaMap=n.alphaMap,p.transparent=n.transparent||n.transmission>0,p.isShadowPassMaterial&&(p.side=n.shadowSide===null?n.side:n.shadowSide,n.depthNode&&n.depthNode.isNode&&(d=p.depthNode,p.depthNode=n.depthNode),n.castShadowNode&&n.castShadowNode.isNode&&(u=p.colorNode,p.colorNode=n.castShadowNode),n.castShadowPositionNode&&n.castShadowPositionNode.isNode&&(h=p.positionNode,p.positionNode=n.castShadowPositionNode)),n=p}n.transparent===!0&&n.side===Jn&&n.forceSinglePass===!1?(n.side=Gt,this._handleObjectFunction(e,n,t,s,a,r,l,"backSide"),n.side=Qs,this._handleObjectFunction(e,n,t,s,a,r,l,c),n.side=Jn):this._handleObjectFunction(e,n,t,s,a,r,l,c),h!==void 0&&(t.overrideMaterial.positionNode=h),d!==void 0&&(t.overrideMaterial.depthNode=d),u!==void 0&&(t.overrideMaterial.colorNode=u),e.onAfterRender(this,t,s,i,n,r)}_renderObjectDirect(e,t,s,i,n,r,a,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=r;const h=this._nodes.needsRefresh(c);h&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup),this.backend.draw(c,this.info),h&&this._nodes.updateAfter(c)}_createObjectPipeline(e,t,s,i,n,r,a,l){const c=this._objects.get(e,t,s,i,n,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=r,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}get compile(){return this.compileAsync}}class Qu{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}function TA(o){return o+(Ci-o%Ci)%Ci}class Dy extends Qu{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return TA(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class Oy extends Dy{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let SA=0;class By extends Oy{constructor(e,t){super("UniformBuffer_"+SA++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class vA extends Oy{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const n=this.uniforms[s],r=n.boundary,a=n.itemSize*e,l=t%Ci,c=l%r,h=l+c;t+=c,h!==0&&Ci-h<a&&(t+=Ci-h),n.offset=t/e,t+=a}return Math.ceil(t/Ci)*Ci}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);console.error("THREE.WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n]!==i){const a=this._getBufferForType(r);a[n]=s[n]=i,t=!0}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,t=!0}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,a[n+2]=s[n+2]=i.z,t=!0}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset,r=e.getType();if(s[n+0]!==i.x||s[n+1]!==i.y||s[n+2]!==i.z||s[n+4]!==i.w){const a=this._getBufferForType(r);a[n+0]=s[n+0]=i.x,a[n+1]=s[n+1]=i.y,a[n+2]=s[n+2]=i.z,a[n+3]=s[n+3]=i.w,t=!0}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),n=e.offset;if(s[n+0]!==i.r||s[n+1]!==i.g||s[n+2]!==i.b){const r=this.buffer;r[n+0]=s[n+0]=i.r,r[n+1]=s[n+1]=i.g,r[n+2]=s[n+2]=i.b,t=!0}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;if(s[n+0]!==i[0]||s[n+1]!==i[1]||s[n+2]!==i[2]||s[n+4]!==i[3]||s[n+5]!==i[4]||s[n+6]!==i[5]||s[n+8]!==i[6]||s[n+9]!==i[7]||s[n+10]!==i[8]){const r=this.buffer;r[n+0]=s[n+0]=i[0],r[n+1]=s[n+1]=i[1],r[n+2]=s[n+2]=i[2],r[n+4]=s[n+4]=i[3],r[n+5]=s[n+5]=i[4],r[n+6]=s[n+6]=i[5],r[n+8]=s[n+8]=i[6],r[n+9]=s[n+9]=i[7],r[n+10]=s[n+10]=i[8],t=!0}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,n=e.offset;return MA(s,i,n)===!1&&(this.buffer.set(i,n),wA(s,i,n),t=!0),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function wA(o,e,t){for(let s=0,i=e.length;s<i;s++)o[t+s]=e[s]}function MA(o,e,t){for(let s=0,i=e.length;s<i;s++)if(o[t+s]!==e[s])return!1;return!0}let CA=0;class Iy extends vA{constructor(e,t){super(e),this.id=CA++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let EA=0;class AA extends Qu{constructor(e,t){super(e),this.id=EA++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}}class Pl extends AA{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Ly extends Pl{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Uy extends Pl{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}class RA extends St{constructor(e=null,t=1,s=1,i,n,r,a,l,c=ut,h=ut,u,d){super(null,r,a,l,c,h,i,n,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const NA={textureDimensions:"textureSize",equals:"equal"},PA={low:"lowp",medium:"mediump",high:"highp"},yf={swizzleAssign:!0,storageBuffer:!1},xf={perspective:"smooth",linear:"noperspective"},_f={centroid:"centroid","flat first":"flat","flat either":"flat"},bf=`
|
|
126
126
|
precision highp float;
|
|
127
127
|
precision highp int;
|
|
128
128
|
precision highp sampler2D;
|
|
@@ -143,18 +143,18 @@ precision highp isampler2DArray;
|
|
|
143
143
|
precision lowp sampler2DShadow;
|
|
144
144
|
precision lowp sampler2DArrayShadow;
|
|
145
145
|
precision lowp samplerCubeShadow;
|
|
146
|
-
`;class
|
|
146
|
+
`;class FA extends Cy{constructor(e,t){super(e,t,new zE),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==ri}getMethod(e){return NA[e]||e}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const r of t.inputs)i.push(this.getType(r.type)+" "+r.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {
|
|
147
147
|
|
|
148
148
|
${s.vars}
|
|
149
149
|
|
|
150
150
|
${s.code}
|
|
151
151
|
return ${s.result};
|
|
152
152
|
|
|
153
|
-
}`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const s=t.array,i=t.count*t.itemSize,{itemSize:n}=t,r=t.array.constructor.name.toLowerCase().includes("int");let a=r?
|
|
153
|
+
}`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const s=t.array,i=t.count*t.itemSize,{itemSize:n}=t,r=t.array.constructor.name.toLowerCase().includes("int");let a=r?ou:ru;n===2?a=r?au:cn:n===3?a=r?G_:nu:n===4&&(a=r?lu:os);const l={Float32Array:Kt,Uint8Array:Nt,Uint16Array:jn,Uint32Array:Xe,Int8Array:co,Int16Array:ho,Int32Array:Et,Uint8ClampedArray:Nt},c=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/n))));let h=Math.ceil(i/n/c);c*h*n<i&&h++;const u=c*h*n,d=new s.constructor(u);d.set(s,0),t.array=d;const p=new RA(t.array,c,h,a,l[t.array.constructor.name]||Kt);p.needsUpdate=!0,p.isPBOTexture=!0;const f=new br(p,null,null);f.setPrecision("high"),t.pboNode=f,t.pbo=f.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){const h=this.renderer.backend.get(i);h.pbo=i.pbo}const n=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.label),r=this.getPropertyName(n);this.increaseUsage(s);const a=s.build(this,"uint"),l=this.getDataFromNode(e);let c=l.propertyName;if(c===void 0){const h=this.getVarFromNode(e);c=this.getPropertyName(h);const u=this.getDataFromNode(t);let d=u.propertySizeName;d===void 0&&(d=c+"Size",this.getVarFromNode(t,d,"uint"),this.addLineFlowCode(`${d} = uint( textureSize( ${r}, 0 ).x )`,e),u.propertySizeName=d);const{itemSize:p}=i,f="."+_r.join("").slice(0,p),m=`ivec2(${a} % ${d}, ${a} / ${d})`,x=this.generateTextureLoad(null,r,m,null,"0");let g="vec4";i.pbo.type===Xe?g="uvec4":i.pbo.type===Et&&(g="ivec4"),this.addLineFlowCode(`${c} = ${g}(${x})${f}`,e),l.propertyName=c}return c}generateTextureLoad(e,t,s,i,n="0"){return i?`texelFetch( ${t}, ivec3( ${s}, ${i} ), ${n} )`:`texelFetch( ${t}, ${s}, ${n} )`}generateTexture(e,t,s,i){return e.isDepthTexture?(i&&(s=`vec4( ${s}, ${i} )`),`texture( ${t}, ${s} ).x`):(i&&(s=`vec3( ${s}, ${i} )`),`texture( ${t}, ${s} )`)}generateTextureLevel(e,t,s,i){return`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i){return`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i){return`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return n?`texture( ${t}, vec4( ${s}, ${n}, ${i} ) )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${r} shader.`)}getVars(e){const t=[],s=this.vars[e];if(s!==void 0)for(const i of s)t.push(`${this.getVar(i.type,i.name,i.count)};`);return t.join(`
|
|
154
154
|
`)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const r of t){let a=null,l=!1;if(r.type==="texture"||r.type==="texture3D"){const h=r.node.value;let u="";(h.isDataTexture===!0||h.isData3DTexture===!0)&&(h.type===Xe?u="u":h.type===Et&&(u="i")),r.type==="texture3D"&&h.isArrayTexture===!1?a=`${u}sampler3D ${r.name};`:h.compareFunction?h.isArrayTexture===!0?a=`sampler2DArrayShadow ${r.name};`:a=`sampler2DShadow ${r.name};`:h.isArrayTexture===!0||h.isDataArrayTexture===!0||h.isCompressedArrayTexture===!0?a=`${u}sampler2DArray ${r.name};`:a=`${u}sampler2D ${r.name};`}else if(r.type==="cubeTexture")a=`samplerCube ${r.name};`;else if(r.type==="buffer"){const h=r.node,u=this.getType(h.bufferType),d=h.bufferCount,p=d>0?d:"";a=`${h.name} {
|
|
155
155
|
${u} ${r.name}[${p}];
|
|
156
156
|
};
|
|
157
|
-
`}else a=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,l=!0;const c=r.node.precision;if(c!==null&&(a=
|
|
157
|
+
`}else a=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,l=!0;const c=r.node.precision;if(c!==null&&(a=PA[c]+" "+a),l){a=" "+a;const h=r.groupNode.name;(i[h]||(i[h]=[])).push(a)}else a="uniform "+a,s.push(a)}let n="";for(const r in i){const a=i[r];n+=this._getGLSLUniformStruct(e+"_"+r,a.join(`
|
|
158
158
|
`))+`
|
|
159
159
|
`}return n+=s.join(`
|
|
160
160
|
`),n}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Et){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;i instanceof Uint32Array||i instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const s=this.getAttributesArray();let i=0;for(const n of s)t+=`layout( location = ${i++} ) in ${n.type} ${n.name};
|
|
@@ -167,14 +167,14 @@ ${s.code}
|
|
|
167
167
|
`)+`
|
|
168
168
|
|
|
169
169
|
`+t.join(`
|
|
170
|
-
`)}getVaryings(e){let t="";const s=this.varyings;if(e==="vertex"||e==="compute")for(const i of s){e==="compute"&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){const r=
|
|
170
|
+
`)}getVaryings(e){let t="";const s=this.varyings;if(e==="vertex"||e==="compute")for(const i of s){e==="compute"&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){const r=xf[i.interpolationType]||i.interpolationType,a=_f[i.interpolationSampling]||"";t+=`${r} ${a} out ${n} ${i.name};
|
|
171
171
|
`}else{const r=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${r}out ${n} ${i.name};
|
|
172
172
|
`}else t+=`${n} ${i.name};
|
|
173
|
-
`}else if(e==="fragment"){for(const i of s)if(i.needsInterpolation){const n=this.getType(i.type);if(i.interpolationType){const r=
|
|
173
|
+
`}else if(e==="fragment"){for(const i of s)if(i.needsInterpolation){const n=this.getType(i.type);if(i.interpolationType){const r=xf[i.interpolationType]||i.interpolationType,a=_f[i.interpolationSampling]||"";t+=`${r} ${a} in ${n} ${i.name};
|
|
174
174
|
`}else{const r=n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":"";t+=`${r}in ${n} ${i.name};
|
|
175
175
|
`}}}for(const i of this.builtins[e])t+=`${i};
|
|
176
176
|
`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((s,i)=>s*i,1)}u`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);i.has(e)===!1&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const i=this.renderer.backend.extensions;this.object.isBatchedMesh&&i.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(s!==void 0)for(const{name:i,behavior:n}of s.values())t.push(`#extension ${i} : ${n}`);return t.join(`
|
|
177
|
-
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=
|
|
177
|
+
`)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=yf[e];if(t===void 0){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance";break}if(s!==void 0){const i=this.renderer.backend.extensions;i.has(s)&&(i.get(s),t=!0)}yf[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],n=this.getPropertyName(i.attributeNode);n&&(t+=`${i.varyingName} = ${n};
|
|
178
178
|
`)}return t}_getGLSLUniformStruct(e,t){return`
|
|
179
179
|
layout( std140 ) uniform ${e} {
|
|
180
180
|
${t}
|
|
@@ -186,7 +186,7 @@ ${this.getSignature()}
|
|
|
186
186
|
${e.extensions}
|
|
187
187
|
|
|
188
188
|
// precision
|
|
189
|
-
${
|
|
189
|
+
${bf}
|
|
190
190
|
|
|
191
191
|
// uniforms
|
|
192
192
|
${e.uniforms}
|
|
@@ -222,7 +222,7 @@ ${this.getSignature()}
|
|
|
222
222
|
${e.extensions}
|
|
223
223
|
|
|
224
224
|
// precision
|
|
225
|
-
${
|
|
225
|
+
${bf}
|
|
226
226
|
|
|
227
227
|
// uniforms
|
|
228
228
|
${e.uniforms}
|
|
@@ -251,7 +251,7 @@ void main() {
|
|
|
251
251
|
`),s+=` // flow -> ${c}
|
|
252
252
|
`),s+=`${l.code}
|
|
253
253
|
`,a===n&&t!=="compute"&&(s+=`// result
|
|
254
|
-
`,t==="vertex"?(s+="gl_Position = ",s+=`${l.result};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${l.result};`)))}const r=e[t];r.extensions=this.getExtensions(t),r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.vars=this.getVars(t),r.structs=this.getStructs(t),r.codes=this.getCodes(t),r.transforms=this.getTransforms(t),r.flow=s}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),r=this.getDataFromNode(e,s,this.globalCache);let a=r.uniformGPU;if(a===void 0){const l=e.groupNode,c=l.name,h=this.getBindGroupArray(c,s);if(t==="texture")a=new Al(n.name,n.node,l),h.push(a);else if(t==="cubeTexture")a=new Dy(n.name,n.node,l),h.push(a);else if(t==="texture3D")a=new Oy(n.name,n.node,l),h.push(a);else if(t==="buffer"){e.name=`NodeBuffer_${e.id}`,n.name=`buffer${e.id}`;const u=new Py(e,l);u.name=e.name,h.push(u),a=u}else{const u=this.uniformGroups[s]||(this.uniformGroups[s]={});let d=u[c];d===void 0&&(d=new Fy(s+"_"+c,l),u[c]=d,h.push(d)),a=this.getNodeUniform(n,t),d.addUniform(a)}r.uniformGPU=a}return n}}let kc=null,Un=null;class By{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){oi("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t){oi(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);return}const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return kc=kc||new ce,this.renderer.getDrawingBufferSize(kc)}setScissorTest(){}getClearColor(){const e=this.renderer;return Un=Un||new du,e.getClearColor(Un),Un.getRGB(Un),Un}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:O_(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${gm} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let cA=0;class hA{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class uA{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,n=e.array,r=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,l=s.get(a);let c=l.bufferGPU;c===void 0&&(c=this._createBuffer(i,t,n,r),l.bufferGPU=c,l.bufferType=t,l.version=a.version);let h;if(n instanceof Float32Array)h=i.FLOAT;else if(n instanceof Uint16Array)e.isFloat16BufferAttribute?h=i.HALF_FLOAT:h=i.UNSIGNED_SHORT;else if(n instanceof Int16Array)h=i.SHORT;else if(n instanceof Uint32Array)h=i.UNSIGNED_INT;else if(n instanceof Int32Array)h=i.INT;else if(n instanceof Int8Array)h=i.BYTE;else if(n instanceof Uint8Array)h=i.UNSIGNED_BYTE;else if(n instanceof Uint8ClampedArray)h=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+n);let u={bufferGPU:c,bufferType:t,type:h,byteLength:n.byteLength,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Et,id:cA++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,n,r);u=new hA(u,d)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,n=e.isInterleavedBufferAttribute?e.data:e,r=t.get(n),a=r.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,r.bufferGPU),l.length===0)s.bufferSubData(a,0,i);else{for(let c=0,h=l.length;c<h;c++){const u=l[c];s.bufferSubData(a,u.start*i.BYTES_PER_ELEMENT,i,u.start,u.count)}n.clearUpdateRanges()}s.bindBuffer(a,null),r.version=n.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:n}=t.get(i),r=e.array,a=r.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,n);const l=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.bufferData(s.COPY_WRITE_BUFFER,a,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const c=new e.array.constructor(r.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,c),s.deleteBuffer(l),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),c.buffer}_createBuffer(e,t,s,i){const n=e.createBuffer();return e.bindBuffer(t,n),e.bufferData(t,s,i),e.bindBuffer(t,null),n}}let zc,Vr;class dA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;zc={[bs]:e.FUNC_ADD,[ym]:e.FUNC_SUBTRACT,[xm]:e.FUNC_REVERSE_SUBTRACT},Vr={[vi]:e.ZERO,[_m]:e.ONE,[bm]:e.SRC_COLOR,[ja]:e.SRC_ALPHA,[Cm]:e.SRC_ALPHA_SATURATE,[wm]:e.DST_COLOR,[Sm]:e.DST_ALPHA,[Tm]:e.ONE_MINUS_SRC_COLOR,[qa]:e.ONE_MINUS_SRC_ALPHA,[Mm]:e.ONE_MINUS_DST_COLOR,[vm]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=new ge().fromArray(t),this.currentViewport=new ge().fromArray(s),this._tempVec4=new ge}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==Jx?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===e_?t.cullFace(t.BACK):e===t_?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setBlending(e,t,s,i,n,r,a,l){const{gl:c}=this;if(e===lr){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==oo){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==bs||this.currentBlendEquationAlpha!==bs)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=bs,this.currentBlendEquationAlpha=bs),l)switch(e){case Js:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Ha:c.blendFunc(c.ONE,c.ONE);break;case Wa:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case $a:c.blendFuncSeparate(c.ZERO,c.SRC_COLOR,c.ZERO,c.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e);break}else switch(e){case Js:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case Ha:c.blendFunc(c.SRC_ALPHA,c.ONE);break;case Wa:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case $a:c.blendFunc(c.ZERO,c.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}n=n||t,r=r||s,a=a||i,(t!==this.currentBlendEquation||n!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(zc[t],zc[n]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=n),(s!==this.currentBlendSrc||i!==this.currentBlendDst||r!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(Vr[s],Vr[i],Vr[r],Vr[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=r,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Em:t.depthFunc(t.NEVER);break;case Am:t.depthFunc(t.ALWAYS);break;case Rm:t.depthFunc(t.LESS);break;case Ya:t.depthFunc(t.LEQUAL);break;case Nm:t.depthFunc(t.EQUAL);break;case Pm:t.depthFunc(t.GEQUAL);break;case Fm:t.depthFunc(t.GREATER);break;case Dm:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentScissor.equals(n)===!1){const{gl:r}=this;r.scissor(n.x,n.y,n.z,n.w),this.currentScissor.copy(n)}}viewport(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentViewport.equals(n)===!1){const{gl:r}=this;r.viewport(n.x,n.y,n.z,n.w),this.currentViewport.copy(n)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==s)&&(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==s)&&(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;e.side===Qn?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let n=e.side===Vt;t&&(n=!n),this.setFlipSided(n),e.blending===Js&&e.transparent===!1?this.setBlending(lr):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const r=e.stencilWrite;if(this.setStencilTest(r),r&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.samples>1?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s)for(let l=0;l<8;l++)l<s?this.enable(12288+l):this.disable(12288+l)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==s)&&(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const s=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(s.bindVertexArray(e),t!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t?(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:s}=this;let i=[],n=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));const r=e.textures;if(i.length!==r.length||i[0]!==s.COLOR_ATTACHMENT0){for(let a=0,l=r.length;a<l;a++)i[a]=s.COLOR_ATTACHMENT0+a;i.length=r.length,n=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,n=!0);n&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:n,currentBoundTextures:r,maxTextures:a}=this;s===void 0&&(n===null?s=i.TEXTURE0+a-1:s=n);let l=r[s];l===void 0&&(l={type:void 0,texture:void 0},r[s]=l),(l.type!==e||l.texture!==t)&&(n!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),l.type=e,l.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,n=`${e}-${t}`;return this.currentBoundBufferBases[n]!==s?(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[n]=s,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class pA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=ri){const{gl:s,extensions:i}=this;let n;const r=Ue.getTransfer(t);if(e===Nt)return s.UNSIGNED_BYTE;if(e===f_)return s.UNSIGNED_SHORT_4_4_4_4;if(e===m_)return s.UNSIGNED_SHORT_5_5_5_1;if(e===Bm)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===ao)return s.BYTE;if(e===lo)return s.SHORT;if(e===$n)return s.UNSIGNED_SHORT;if(e===Et)return s.INT;if(e===Xe)return s.UNSIGNED_INT;if(e===Qt)return s.FLOAT;if(e===rs)return s.HALF_FLOAT;if(e===g_)return s.ALPHA;if(e===su)return s.RGB;if(e===os)return s.RGBA;if(e===Bs)return s.DEPTH_COMPONENT;if(e===ti)return s.DEPTH_STENCIL;if(e===iu)return s.RED;if(e===nu)return s.RED_INTEGER;if(e===cn)return s.RG;if(e===ru)return s.RG_INTEGER;if(e===ou)return s.RGBA_INTEGER;if(e===zl||e===Ra||e===Na||e===Pa)if(r===te)if(n=i.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(e===zl)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Ra)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Na)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Pa)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=i.get("WEBGL_compressed_texture_s3tc"),n!==null){if(e===zl)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Ra)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Na)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Pa)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Ed||e===Ad||e===Rd||e===Nd)if(n=i.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(e===Ed)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Ad)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Rd)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Nd)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Pd||e===gh||e===yh)if(n=i.get("WEBGL_compressed_texture_etc"),n!==null){if(e===Pd||e===gh)return r===te?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(e===yh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(e===xh||e===_h||e===bh||e===Th||e===Sh||e===vh||e===wh||e===Mh||e===Ch||e===Eh||e===Ah||e===Rh||e===Nh||e===Ph)if(n=i.get("WEBGL_compressed_texture_astc"),n!==null){if(e===xh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===_h)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===bh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Th)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Sh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===vh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===wh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Mh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Ch)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Eh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Ah)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Rh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Nh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Ph)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Vl)if(n=i.get("EXT_texture_compression_bptc"),n!==null){if(e===Vl)return r===te?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===x_||e===Fd||e===Dd||e===Od)if(n=i.get("EXT_texture_compression_rgtc"),n!==null){if(e===Vl)return n.COMPRESSED_RED_RGTC1_EXT;if(e===Fd)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Dd)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Od)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Fi?s.UNSIGNED_INT_24_8:s[e]!==void 0?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{function n(){const r=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(r===e.WAIT_FAILED){e.deleteSync(t),i();return}if(r===e.TIMEOUT_EXPIRED){requestAnimationFrame(n);return}e.deleteSync(t),s()}n()})}}let xf=!1,fa,Vc,_f;class fA{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},xf===!1&&(this._init(),xf=!0)}_init(){const e=this.gl;fa={[cr]:e.REPEAT,[Ri]:e.CLAMP_TO_EDGE,[hr]:e.MIRRORED_REPEAT},Vc={[ut]:e.NEAREST,[Om]:e.NEAREST_MIPMAP_NEAREST,[xo]:e.NEAREST_MIPMAP_LINEAR,[Kt]:e.LINEAR,[mh]:e.LINEAR_MIPMAP_NEAREST,[ei]:e.LINEAR_MIPMAP_LINEAR},_f={[Im]:e.NEVER,[Gm]:e.ALWAYS,[au]:e.LESS,[Um]:e.LEQUAL,[Lm]:e.EQUAL,[Vm]:e.GEQUAL,[km]:e.GREATER,[zm]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return e.isCubeTexture===!0?s=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?s=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?s=t.TEXTURE_3D:s=t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,n=!1){const{gl:r,extensions:a}=this;if(e!==null){if(r[e]!==void 0)return r[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=t;if(t===r.RED&&(s===r.FLOAT&&(l=r.R32F),s===r.HALF_FLOAT&&(l=r.R16F),s===r.UNSIGNED_BYTE&&(l=r.R8),s===r.UNSIGNED_SHORT&&(l=r.R16),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RED_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.R8UI),s===r.UNSIGNED_SHORT&&(l=r.R16UI),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RG&&(s===r.FLOAT&&(l=r.RG32F),s===r.HALF_FLOAT&&(l=r.RG16F),s===r.UNSIGNED_BYTE&&(l=r.RG8),s===r.UNSIGNED_SHORT&&(l=r.RG16),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RG_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RG8UI),s===r.UNSIGNED_SHORT&&(l=r.RG16UI),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RGB){const c=n?Za:Ue.getTransfer(i);s===r.FLOAT&&(l=r.RGB32F),s===r.HALF_FLOAT&&(l=r.RGB16F),s===r.UNSIGNED_BYTE&&(l=r.RGB8),s===r.UNSIGNED_SHORT&&(l=r.RGB16),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I),s===r.UNSIGNED_BYTE&&(l=c===te?r.SRGB8:r.RGB8),s===r.UNSIGNED_SHORT_5_6_5&&(l=r.RGB565),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGB4),s===r.UNSIGNED_INT_5_9_9_9_REV&&(l=r.RGB9_E5)}if(t===r.RGB_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGB8UI),s===r.UNSIGNED_SHORT&&(l=r.RGB16UI),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I)),t===r.RGBA){const c=n?Za:Ue.getTransfer(i);s===r.FLOAT&&(l=r.RGBA32F),s===r.HALF_FLOAT&&(l=r.RGBA16F),s===r.UNSIGNED_BYTE&&(l=r.RGBA8),s===r.UNSIGNED_SHORT&&(l=r.RGBA16),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I),s===r.UNSIGNED_BYTE&&(l=c===te?r.SRGB8_ALPHA8:r.RGBA8),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGBA4),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1)}return t===r.RGBA_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGBA8UI),s===r.UNSIGNED_SHORT&&(l=r.RGBA16UI),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I)),t===r.DEPTH_COMPONENT&&(s===r.UNSIGNED_SHORT&&(l=r.DEPTH_COMPONENT16),s===r.UNSIGNED_INT&&(l=r.DEPTH_COMPONENT24),s===r.FLOAT&&(l=r.DEPTH_COMPONENT32F)),t===r.DEPTH_STENCIL&&s===r.UNSIGNED_INT_24_8&&(l=r.DEPTH24_STENCIL8),(l===r.R16F||l===r.R32F||l===r.RG16F||l===r.RG32F||l===r.RGBA16F||l===r.RGBA32F)&&a.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:n}=this,r=Ue.getPrimaries(Ue.workingColorSpace),a=t.colorSpace===ri?null:Ue.getPrimaries(t.colorSpace),l=t.colorSpace===ri||r===a?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),s.texParameteri(e,s.TEXTURE_WRAP_S,fa[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,fa[t.wrapT]),(e===s.TEXTURE_3D||e===s.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,fa[t.wrapR])),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Vc[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,h=t.minFilter===Kt&&c?ei:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Vc[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,_f[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===ut||t.minFilter!==xo&&t.minFilter!==ei||t.type===Qt&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const u=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,u.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,n.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,n=this.getGLTextureType(e);let r=i[n];r===void 0&&(r=t.createTexture(),s.state.bindTexture(n,r),t.texParameteri(n,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(n,t.TEXTURE_MAG_FILTER,t.NEAREST),i[n]=r),s.set(e,{textureGPU:r,glTextureType:n,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:n,width:r,height:a,depth:l}=t,c=i.utils.convert(e.format,e.colorSpace),h=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,c,h,e.colorSpace,e.isVideoTexture),d=s.createTexture(),p=this.getGLTextureType(e);i.state.bindTexture(p,d),this.setTextureParameters(p,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,n,u,r,a,l):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,n,u,r,a,l):e.isVideoTexture||s.texStorage2D(p,n,u,r,a),i.set(e,{textureGPU:d,glTextureType:p,glFormat:c,glType:h,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:n,glTextureType:r,glFormat:a,glType:l}=i.get(t),{width:c,height:h}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(r,n),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(r,0,0,0,c,h,a,l,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:n}=t,{textureGPU:r,glTextureType:a,glFormat:l,glType:c,glInternalFormat:h}=this.backend.get(e);if(!(e.isRenderTargetTexture||r===void 0))if(this.backend.state.bindTexture(a,r),this.setTextureParameters(a,e),e.isCompressedTexture){const u=e.mipmaps,d=t.image;for(let p=0;p<u.length;p++){const f=u[p];e.isCompressedArrayTexture?e.format!==s.RGBA?l!==null?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,f.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,c,f.data):l!==null?s.compressedTexSubImage2D(s.TEXTURE_2D,p,0,0,f.width,f.height,l,f.data):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const u=t.images;for(let d=0;d<6;d++){const p=bf(u[d]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,0,0,0,i,n,l,c,p)}}else if(e.isDataArrayTexture||e.isArrayTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isData3DTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,h,l,c,t.image);else{const u=bf(t.image);s.texSubImage2D(a,0,0,0,i,n,l,c,u)}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:n}=s.get(e);s.state.bindTexture(n,i),t.generateMipmap(n)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const n in i.framebuffers)t.deleteFramebuffer(i.framebuffers[n]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let n=0;n<i.msaaRenderbuffers.length;n++)t.deleteRenderbuffer(i.msaaRenderbuffers[n]);delete i.msaaRenderbuffers}}}destroyTexture(e){const{gl:t,backend:s}=this,{textureGPU:i,renderTarget:n}=s.get(e);this.deallocateRenderBuffers(n),t.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){const{gl:a,backend:l}=this,{state:c}=this.backend,{textureGPU:h,glTextureType:u,glType:d,glFormat:p}=l.get(t);c.bindTexture(u,h);let f,m,y,g,_,b,T,S,C;const w=e.isCompressedTexture?e.mipmaps[r]:e.image;if(s!==null)f=s.max.x-s.min.x,m=s.max.y-s.min.y,y=s.isBox3?s.max.z-s.min.z:1,g=s.min.x,_=s.min.y,b=s.isBox3?s.min.z:0;else{const X=Math.pow(2,-n);f=Math.floor(w.width*X),m=Math.floor(w.height*X),e.isDataArrayTexture||e.isArrayTexture?y=w.depth:e.isData3DTexture?y=Math.floor(w.depth*X):y=1,g=0,_=0,b=0}i!==null?(T=i.x,S=i.y,C=i.z):(T=0,S=0,C=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const R=a.getParameter(a.UNPACK_ROW_LENGTH),P=a.getParameter(a.UNPACK_IMAGE_HEIGHT),z=a.getParameter(a.UNPACK_SKIP_PIXELS),$=a.getParameter(a.UNPACK_SKIP_ROWS),q=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,w.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,g),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const j=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const X=l.get(e),Z=l.get(t),we=l.get(X.renderTarget),ue=l.get(Z.renderTarget),ye=we.framebuffers[X.cacheKey],se=ue.framebuffers[Z.cacheKey];c.bindFramebuffer(a.READ_FRAMEBUFFER,ye),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,se);let Me=a.COLOR_BUFFER_BIT;e.isDepthTexture&&(Me=a.DEPTH_BUFFER_BIT),a.blitFramebuffer(g,_,f,m,T,S,f,m,Me,a.NEAREST),c.bindFramebuffer(a.READ_FRAMEBUFFER,null),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else j?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,r,T,S,C,f,m,y,p,d,w.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,r,T,S,C,f,m,y,p,w.data):a.texSubImage3D(u,r,T,S,C,f,m,y,p,d,w):e.isDataTexture?a.texSubImage2D(u,r,T,S,f,m,p,d,w.data):e.isCompressedTexture?a.compressedTexSubImage2D(u,r,T,S,w.width,w.height,p,w.data):a.texSubImage2D(u,r,T,S,f,m,p,d,w);a.pixelStorei(a.UNPACK_ROW_LENGTH,R),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,P),a.pixelStorei(a.UNPACK_SKIP_PIXELS,z),a.pixelStorei(a.UNPACK_SKIP_ROWS,$),a.pixelStorei(a.UNPACK_SKIP_IMAGES,q),r===0&&t.generateMipmaps&&a.generateMipmap(u),c.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:n}=this.backend,{textureGPU:r}=this.backend.get(e),{x:a,y:l,z:c,w:h}=s,u=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const p=a!==0||l!==0;let f,m;if(e.isDepthTexture===!0?(f=i.DEPTH_BUFFER_BIT,m=i.DEPTH_ATTACHMENT,t.stencil&&(f|=i.STENCIL_BUFFER_BIT)):(f=i.COLOR_BUFFER_BIT,m=i.COLOR_ATTACHMENT0),p){const y=this.backend.get(t.renderTarget),g=y.framebuffers[t.getCacheKey()],_=y.msaaFrameBuffer;n.bindFramebuffer(i.DRAW_FRAMEBUFFER,g),n.bindFramebuffer(i.READ_FRAMEBUFFER,_);const b=d-l-h;i.blitFramebuffer(a,b,a+c,b+h,a,b,a+c,b+h,f,i.NEAREST),n.bindFramebuffer(i.READ_FRAMEBUFFER,g),n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,b,c,h),n.unbindTexture()}else{const y=i.createFramebuffer();n.bindFramebuffer(i.DRAW_FRAMEBUFFER,y),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,m,i.TEXTURE_2D,r,0),i.blitFramebuffer(0,0,c,h,0,0,c,h,f,i.NEAREST),i.deleteFramebuffer(y)}}else n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,d-h-l,c,h),n.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:n}=this,r=t.renderTarget,{depthTexture:a,depthBuffer:l,stencilBuffer:c,width:h,height:u}=r;if(n.bindRenderbuffer(n.RENDERBUFFER,e),l&&!c){let d=n.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(n.RENDERBUFFER,r.samples,d,h,u):s>0?(a&&a.isDepthTexture&&a.type===n.FLOAT&&(d=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,s,d,h,u)):n.renderbufferStorage(n.RENDERBUFFER,d,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else l&&c&&(s>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,s,n.DEPTH24_STENCIL8,h,u):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,n,r){const{backend:a,gl:l}=this,{textureGPU:c,glFormat:h,glType:u}=this.backend.get(e),d=l.createFramebuffer();l.bindFramebuffer(l.READ_FRAMEBUFFER,d);const p=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+r:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,p,c,0);const f=this._getTypedArrayType(u),m=this._getBytesPerTexel(u,h),g=i*n*m,_=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.bufferData(l.PIXEL_PACK_BUFFER,g,l.STREAM_READ),l.readPixels(t,s,i,n,h,u,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const b=new f(g/f.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,b),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteFramebuffer(d),b}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;if(e===s.UNSIGNED_BYTE&&(i=1),(e===s.UNSIGNED_SHORT_4_4_4_4||e===s.UNSIGNED_SHORT_5_5_5_1||e===s.UNSIGNED_SHORT_5_6_5||e===s.UNSIGNED_SHORT||e===s.HALF_FLOAT)&&(i=2),(e===s.UNSIGNED_INT||e===s.FLOAT)&&(i=4),t===s.RGBA)return i*4;if(t===s.RGB)return i*3;if(t===s.ALPHA)return i}}function bf(o){return o.isDataTexture?o.image.data:typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas?o:o.data}class mA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class gA{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const Tf={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class yA{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:n,type:r,info:a,index:l}=this;l!==0?s.drawElements(i,t,r,e):s.drawArrays(i,e,t),a.update(n,t,1)}renderInstances(e,t,s){const{gl:i,mode:n,type:r,index:a,object:l,info:c}=this;s!==0&&(a!==0?i.drawElementsInstanced(n,t,r,e,s):i.drawArraysInstanced(n,e,t,s),c.update(l,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:n,object:r,info:a}=this;if(s===0)return;const l=i.get("WEBGL_multi_draw");if(l===null)for(let c=0;c<s;c++)this.render(e[c],t[c]);else{this.index!==0?l.multiDrawElementsWEBGL(n,t,0,this.type,e,0,s):l.multiDrawArraysWEBGL(n,e,0,t,0,s);let c=0;for(let h=0;h<s;h++)c+=t[h];a.update(r,c,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:n,mode:r,object:a,info:l}=this;if(s===0)return;const c=n.get("WEBGL_multi_draw");if(c===null)for(let h=0;h<s;h++)this.renderInstances(e[h],t[h],i[h]);else{this.index!==0?c.multiDrawElementsInstancedWEBGL(r,t,0,this.type,e,0,i,0,s):c.multiDrawArraysInstancedWEBGL(r,e,0,t,0,i,0,s);let h=0;for(let u=0;u<s;u++)h+=t[u]*i[u];l.update(a,h,1)}}}class Iy{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class xA extends Iy{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){console.warn("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return oi(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(t==null||this.activeQuery!==null)return;const s=this.queries[t];if(s)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){console.error("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(s){console.error("Error in endQuery:",s),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[i,n]of this.queryStates)if(n==="ended"){const r=this.queries[i];e.push(this.resolveQuery(r))}if(e.length===0)return this.lastValue;const s=(await Promise.all(e)).reduce((i,n)=>i+n,0);return this.lastValue=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let s,i=!1;const n=()=>{s&&(clearTimeout(s),s=null)},r=l=>{i||(i=!0,n(),t(l))},a=()=>{if(this.isDisposed){r(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){r(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){s=setTimeout(a,1);return}const h=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(h)/1e6)}catch(l){console.error("Error checking query:",l),t(this.lastValue)}};a()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const Sf=new ce;class vf extends By{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",s);function n(r){r.preventDefault();const a={api:"WebGL",message:r.statusMessage||"Unknown reason",reason:null,originalEvent:r};e.onDeviceLost(a)}this._onContextLost=n,e.domElement.addEventListener("webglcontextlost",n,!1),this.gl=i,this.extensions=new mA(this),this.capabilities=new gA(this),this.attributeUtils=new uA(this),this.textureUtils=new fA(this),this.bufferRenderer=new yA(this),this.state=new dA(this),this.utils=new pA(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return Ut}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),s!==null){const n=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:n}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e.autoAllocateDepthBuffer===!0&&e.multiview===!1&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e.autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new xA(this.gl,t,2048));const s=this.timestampQueryPool[t];s.allocateQueriesForContext(e)!==null&&s.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:n,height:r}=this.getDrawingBufferSize(Sf);t.viewport(0,0,n,r)}if(e.scissor){const{x:n,y:r,width:a,height:l}=e.scissorValue;t.scissor(n,e.height-l-r,a,l)}this.initTimestampQuery(e),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),n=i.previousContext;s.resetVertexState();const r=e.occlusionQueryCount;r>0&&(r>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(a!==null)for(let l=0;l<a.length;l++){const c=a[l];c.generateMipmaps&&this.generateMipmaps(c)}if(this._currentContext=n,e.textures!==null&&e.renderTarget){const l=this.get(e.renderTarget),{resolveDepthBuffer:c,samples:h}=e.renderTarget;if(h>0&&this._useMultisampledExtension(e.renderTarget)===!1){const u=l.framebuffers[e.getCacheKey()],d=t.COLOR_BUFFER_BIT,p=l.msaaFrameBuffer,f=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,p),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u);for(let m=0;m<f.length;m++)if(e.scissor){const{x:y,y:g,width:_,height:b}=e.scissorValue,T=e.height-b-g;t.blitFramebuffer(y,T,y+_,T+b,y,T,y+_,T+b,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateSubFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray,y,T,_,b)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray)}else if(c===!1&&l.framebuffers){const u=l.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,l.depthInvalidationArray)}}if(n!==null)if(this._setFramebuffer(n),n.viewport)this.updateViewport(n);else{const{width:l,height:c}=this.getDrawingBufferSize(Sf);s.viewport(0,0,l,c)}this.prepareTimestampBuffer(e)}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const a=()=>{let l=0;for(let c=0;c<s.length;c++){const h=s[c];h!==null&&r.getQueryParameter(h,r.QUERY_RESULT_AVAILABLE)&&(r.getQueryParameter(h,r.QUERY_RESULT)===0&&n.add(i[c]),s[c]=null,r.deleteQuery(h),l++)}l<s.length?requestAnimationFrame(a):t.occluded=n};a()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:n,height:r}=e.viewportValue;t.viewport(s,e.height-r-i,n,r)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,n=!0){const{gl:r,renderer:a}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let l=0;if(e&&(l|=r.COLOR_BUFFER_BIT),t&&(l|=r.DEPTH_BUFFER_BIT),s&&(l|=r.STENCIL_BUFFER_BIT),l!==0){let c;i.clearColorValue?c=i.clearColorValue:c=this.getClearColor();const h=a.getClearDepth(),u=a.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)r.clearColor(c.r,c.g,c.b,c.a),r.clear(l);else{if(n&&this._setFramebuffer(i),e)for(let d=0;d<i.textures.length;d++)d===0?r.clearBufferfv(r.COLOR,d,[c.r,c.g,c.b,c.a]):r.clearBufferfv(r.COLOR,d,[0,0,0,1]);t&&s?r.clearBufferfi(r.DEPTH_STENCIL,0,h,u):t?r.clearBufferfv(r.DEPTH,0,[h]):s&&r.clearBufferiv(r.STENCIL,0,[u])}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,s,i){const{state:n,gl:r}=this;this.discard===!1&&(r.enable(r.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:l,attributes:c}=this.get(i),h=this._getVaoKey(c),u=this.vaoCache[h];u===void 0?this._createVao(c):n.setVertexState(u),n.useProgram(a),this._bindUniforms(s);const d=this._getTransformFeedback(l);r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,d),r.beginTransformFeedback(r.POINTS),c[0].isStorageInstancedBufferAttribute?r.drawArraysInstanced(r.POINTS,0,1,t.count):r.drawArrays(r.POINTS,0,t.count),r.endTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null);for(let p=0;p<l.length;p++){const f=l[p];f.pbo&&this.textureUtils.copyBufferToTexture(f.transformBuffer,f.pbo),f.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:n,hardwareClippingPlanes:r}=e,{programGPU:a}=this.get(s),{gl:l,state:c}=this,h=this.get(n),u=e.getDrawParameters();if(u===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinant()<0;c.setMaterial(i,d,r),c.useProgram(a);const p=this.get(e);let f=p.staticVao;if(f===void 0||p.geometryId!==e.geometry.id){const w=this._getVaoKey(e.getAttributes());if(f=this.vaoCache[w],f===void 0){let R;({vaoGPU:f,staticVao:R}=this._createVao(e.getAttributes())),R&&(p.staticVao=f,p.geometryId=e.geometry.id)}}const m=e.getIndex(),y=m!==null?this.get(m).bufferGPU:null;c.setVertexState(f,y);const g=h.lastOcclusionObject;if(g!==t&&g!==void 0){if(g!==null&&g.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),t.occlusionTest===!0){const w=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,w),h.occlusionQueries[h.occlusionQueryIndex]=w,h.occlusionQueryObjects[h.occlusionQueryIndex]=t}h.lastOcclusionObject=t}const _=this.bufferRenderer;t.isPoints?_.mode=l.POINTS:t.isLineSegments?_.mode=l.LINES:t.isLine?_.mode=l.LINE_STRIP:t.isLineLoop?_.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),_.mode=l.LINES):_.mode=l.TRIANGLES;const{vertexCount:b,instanceCount:T}=u;let{firstVertex:S}=u;if(_.object=t,m!==null){S*=m.array.BYTES_PER_ELEMENT;const w=this.get(m);_.index=m.count,_.type=w.type}else _.index=0;const C=()=>{t.isBatchedMesh?t._multiDrawInstances!==null?(oi("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?_.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):oi("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?_.renderInstances(S,b,T):_.render(S,b)};if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const w=this.get(e.camera),R=e.camera.cameras,P=e.getBindingGroup("cameraIndex").bindings[0];if(w.indexesGPU===void 0||w.indexesGPU.length!==R.length){const Z=new Uint32Array([0,0,0,0]),we=[];for(let ue=0,ye=R.length;ue<ye;ue++){const se=l.createBuffer();Z[0]=ue,l.bindBuffer(l.UNIFORM_BUFFER,se),l.bufferData(l.UNIFORM_BUFFER,Z,l.STATIC_DRAW),we.push(se)}w.indexesGPU=we}const z=this.get(P),$=this.renderer.getPixelRatio(),q=this._currentContext.renderTarget,j=this._isRenderCameraDepthArray(this._currentContext),X=this._currentContext.activeCubeFace;if(j){const Z=this.get(q.depthTexture);if(Z.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){Z.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:we}=q;for(let ue=0,ye=R.length;ue<ye;ue++)this.renderer._activeCubeFace=ue,this._currentContext.activeCubeFace=ue,this._setFramebuffer(this._currentContext),this.clear(!1,!0,we,this._currentContext,!1);this.renderer._activeCubeFace=X,this._currentContext.activeCubeFace=X}}for(let Z=0,we=R.length;Z<we;Z++){const ue=R[Z];if(t.layers.test(ue.layers)){j&&(this.renderer._activeCubeFace=Z,this._currentContext.activeCubeFace=Z,this._setFramebuffer(this._currentContext));const ye=ue.viewport;if(ye!==void 0){const se=ye.x*$,Me=ye.y*$,ze=ye.width*$,ot=ye.height*$;c.viewport(Math.floor(se),Math.floor(e.context.height-ot-Me),Math.floor(ze),Math.floor(ot))}c.bindBufferBase(l.UNIFORM_BUFFER,z.index,w.indexesGPU[Z]),C()}this._currentContext.activeCubeFace=X,this.renderer._activeCubeFace=X}}else C()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new lA(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,n=s==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(n,i),t.compileShader(n),this.set(e,{shaderGPU:n})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:n,vertexProgram:r}=i,a=s.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).shaderGPU;if(s.attachShader(a,l),s.attachShader(a,c),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:l,vertexShader:c}),t!==null&&this.parallel){const h=new Promise(u=>{const d=this.parallel,p=()=>{s.getProgramParameter(a,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),u()):requestAnimationFrame(p)};p()});t.push(h);return}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split(`
|
|
254
|
+
`,t==="vertex"?(s+="gl_Position = ",s+=`${l.result};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${l.result};`)))}const r=e[t];r.extensions=this.getExtensions(t),r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.vars=this.getVars(t),r.structs=this.getStructs(t),r.codes=this.getCodes(t),r.transforms=this.getTransforms(t),r.flow=s}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),r=this.getDataFromNode(e,s,this.globalCache);let a=r.uniformGPU;if(a===void 0){const l=e.groupNode,c=l.name,h=this.getBindGroupArray(c,s);if(t==="texture")a=new Pl(n.name,n.node,l),h.push(a);else if(t==="cubeTexture")a=new Ly(n.name,n.node,l),h.push(a);else if(t==="texture3D")a=new Uy(n.name,n.node,l),h.push(a);else if(t==="buffer"){e.name=`NodeBuffer_${e.id}`,n.name=`buffer${e.id}`;const u=new By(e,l);u.name=e.name,h.push(u),a=u}else{const u=this.uniformGroups[s]||(this.uniformGroups[s]={});let d=u[c];d===void 0&&(d=new Iy(s+"_"+c,l),u[c]=d,h.push(d)),a=this.getNodeUniform(n,t),d.addUniform(a)}r.uniformGPU=a}return n}}let Vc=null,kn=null;class ky{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){oi("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t){oi(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);return}const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Vc=Vc||new he,this.renderer.getDrawingBufferSize(Vc)}setScissorTest(){}getClearColor(){const e=this.renderer;return kn=kn||new fu,e.getClearColor(kn),kn.getRGB(kn),kn}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:nb(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${bm} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let DA=0;class OA{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class BA{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,n=e.array,r=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,l=s.get(a);let c=l.bufferGPU;c===void 0&&(c=this._createBuffer(i,t,n,r),l.bufferGPU=c,l.bufferType=t,l.version=a.version);let h;if(n instanceof Float32Array)h=i.FLOAT;else if(n instanceof Uint16Array)e.isFloat16BufferAttribute?h=i.HALF_FLOAT:h=i.UNSIGNED_SHORT;else if(n instanceof Int16Array)h=i.SHORT;else if(n instanceof Uint32Array)h=i.UNSIGNED_INT;else if(n instanceof Int32Array)h=i.INT;else if(n instanceof Int8Array)h=i.BYTE;else if(n instanceof Uint8Array)h=i.UNSIGNED_BYTE;else if(n instanceof Uint8ClampedArray)h=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+n);let u={bufferGPU:c,bufferType:t,type:h,byteLength:n.byteLength,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===Et,id:DA++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,n,r);u=new OA(u,d)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,n=e.isInterleavedBufferAttribute?e.data:e,r=t.get(n),a=r.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,r.bufferGPU),l.length===0)s.bufferSubData(a,0,i);else{for(let c=0,h=l.length;c<h;c++){const u=l[c];s.bufferSubData(a,u.start*i.BYTES_PER_ELEMENT,i,u.start,u.count)}n.clearUpdateRanges()}s.bindBuffer(a,null),r.version=n.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:n}=t.get(i),r=e.array,a=r.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,n);const l=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.bufferData(s.COPY_WRITE_BUFFER,a,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const c=new e.array.constructor(r.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,l),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,c),s.deleteBuffer(l),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),c.buffer}_createBuffer(e,t,s,i){const n=e.createBuffer();return e.bindBuffer(t,n),e.bufferData(t,s,i),e.bindBuffer(t,null),n}}let Hc,Hr;class IA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;Hc={[bs]:e.FUNC_ADD,[Tm]:e.FUNC_SUBTRACT,[Sm]:e.FUNC_REVERSE_SUBTRACT},Hr={[vi]:e.ZERO,[vm]:e.ONE,[wm]:e.SRC_COLOR,[Ya]:e.SRC_ALPHA,[Nm]:e.SRC_ALPHA_SATURATE,[Am]:e.DST_COLOR,[Cm]:e.DST_ALPHA,[Mm]:e.ONE_MINUS_SRC_COLOR,[Xa]:e.ONE_MINUS_SRC_ALPHA,[Rm]:e.ONE_MINUS_DST_COLOR,[Em]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=new ge().fromArray(t),this.currentViewport=new ge().fromArray(s),this._tempVec4=new ge}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==v_?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===w_?t.cullFace(t.BACK):e===M_?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setBlending(e,t,s,i,n,r,a,l){const{gl:c}=this;if(e===hr){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==lo){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==bs||this.currentBlendEquationAlpha!==bs)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=bs,this.currentBlendEquationAlpha=bs),l)switch(e){case Js:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case $a:c.blendFunc(c.ONE,c.ONE);break;case ja:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case qa:c.blendFuncSeparate(c.ZERO,c.SRC_COLOR,c.ZERO,c.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e);break}else switch(e){case Js:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case $a:c.blendFunc(c.SRC_ALPHA,c.ONE);break;case ja:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case qa:c.blendFunc(c.ZERO,c.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}n=n||t,r=r||s,a=a||i,(t!==this.currentBlendEquation||n!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(Hc[t],Hc[n]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=n),(s!==this.currentBlendSrc||i!==this.currentBlendDst||r!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(Hr[s],Hr[i],Hr[r],Hr[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=r,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Pm:t.depthFunc(t.NEVER);break;case Fm:t.depthFunc(t.ALWAYS);break;case Dm:t.depthFunc(t.LESS);break;case Za:t.depthFunc(t.LEQUAL);break;case Om:t.depthFunc(t.EQUAL);break;case Bm:t.depthFunc(t.GEQUAL);break;case Im:t.depthFunc(t.GREATER);break;case Lm:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentScissor.equals(n)===!1){const{gl:r}=this;r.scissor(n.x,n.y,n.z,n.w),this.currentScissor.copy(n)}}viewport(e,t,s,i){const n=this._tempVec4.set(e,t,s,i);if(this.currentViewport.equals(n)===!1){const{gl:r}=this;r.viewport(n.x,n.y,n.z,n.w),this.currentViewport.copy(n)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==s)&&(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==s)&&(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;e.side===Jn?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let n=e.side===Gt;t&&(n=!n),this.setFlipSided(n),e.blending===Js&&e.transparent===!1?this.setBlending(hr):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const r=e.stencilWrite;if(this.setStencilTest(r),r&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.samples>1?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s)for(let l=0;l<8;l++)l<s?this.enable(12288+l):this.disable(12288+l)}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==s)&&(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const s=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(s.bindVertexArray(e),t!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t?(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:s}=this;let i=[],n=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));const r=e.textures;if(i.length!==r.length||i[0]!==s.COLOR_ATTACHMENT0){for(let a=0,l=r.length;a<l;a++)i[a]=s.COLOR_ATTACHMENT0+a;i.length=r.length,n=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,n=!0);n&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:n,currentBoundTextures:r,maxTextures:a}=this;s===void 0&&(n===null?s=i.TEXTURE0+a-1:s=n);let l=r[s];l===void 0&&(l={type:void 0,texture:void 0},r[s]=l),(l.type!==e||l.texture!==t)&&(n!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),l.type=e,l.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,n=`${e}-${t}`;return this.currentBoundBufferBases[n]!==s?(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[n]=s,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class LA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=ri){const{gl:s,extensions:i}=this;let n;const r=Ue.getTransfer(t);if(e===Nt)return s.UNSIGNED_BYTE;if(e===U_)return s.UNSIGNED_SHORT_4_4_4_4;if(e===k_)return s.UNSIGNED_SHORT_5_5_5_1;if(e===km)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===co)return s.BYTE;if(e===ho)return s.SHORT;if(e===jn)return s.UNSIGNED_SHORT;if(e===Et)return s.INT;if(e===Xe)return s.UNSIGNED_INT;if(e===Kt)return s.FLOAT;if(e===rs)return s.HALF_FLOAT;if(e===z_)return s.ALPHA;if(e===nu)return s.RGB;if(e===os)return s.RGBA;if(e===Bs)return s.DEPTH_COMPONENT;if(e===ti)return s.DEPTH_STENCIL;if(e===ru)return s.RED;if(e===ou)return s.RED_INTEGER;if(e===cn)return s.RG;if(e===au)return s.RG_INTEGER;if(e===lu)return s.RGBA_INTEGER;if(e===Hl||e===Pa||e===Fa||e===Da)if(r===te)if(n=i.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(e===Hl)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Pa)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Fa)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Da)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=i.get("WEBGL_compressed_texture_s3tc"),n!==null){if(e===Hl)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Pa)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Fa)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Da)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Nd||e===Pd||e===Fd||e===Dd)if(n=i.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(e===Nd)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Pd)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Fd)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Dd)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Od||e===xh||e===_h)if(n=i.get("WEBGL_compressed_texture_etc"),n!==null){if(e===Od||e===xh)return r===te?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(e===_h)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(e===bh||e===Th||e===Sh||e===vh||e===wh||e===Mh||e===Ch||e===Eh||e===Ah||e===Rh||e===Nh||e===Ph||e===Fh||e===Dh)if(n=i.get("WEBGL_compressed_texture_astc"),n!==null){if(e===bh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Th)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Sh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===vh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===wh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Mh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Ch)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Eh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Ah)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Rh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Nh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ph)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Fh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Dh)return r===te?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Wl)if(n=i.get("EXT_texture_compression_bptc"),n!==null){if(e===Wl)return r===te?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===V_||e===Bd||e===Id||e===Ld)if(n=i.get("EXT_texture_compression_rgtc"),n!==null){if(e===Wl)return n.COMPRESSED_RED_RGTC1_EXT;if(e===Bd)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Id)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Ld)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===Fi?s.UNSIGNED_INT_24_8:s[e]!==void 0?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{function n(){const r=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(r===e.WAIT_FAILED){e.deleteSync(t),i();return}if(r===e.TIMEOUT_EXPIRED){requestAnimationFrame(n);return}e.deleteSync(t),s()}n()})}}let Tf=!1,ma,Wc,Sf;class UA{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},Tf===!1&&(this._init(),Tf=!0)}_init(){const e=this.gl;ma={[ur]:e.REPEAT,[Ri]:e.CLAMP_TO_EDGE,[dr]:e.MIRRORED_REPEAT},Wc={[ut]:e.NEAREST,[Um]:e.NEAREST_MIPMAP_NEAREST,[_o]:e.NEAREST_MIPMAP_LINEAR,[Qt]:e.LINEAR,[yh]:e.LINEAR_MIPMAP_NEAREST,[ei]:e.LINEAR_MIPMAP_LINEAR},Sf={[zm]:e.NEVER,[jm]:e.ALWAYS,[cu]:e.LESS,[Vm]:e.LEQUAL,[Gm]:e.EQUAL,[$m]:e.GEQUAL,[Hm]:e.GREATER,[Wm]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return e.isCubeTexture===!0?s=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?s=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?s=t.TEXTURE_3D:s=t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,n=!1){const{gl:r,extensions:a}=this;if(e!==null){if(r[e]!==void 0)return r[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=t;if(t===r.RED&&(s===r.FLOAT&&(l=r.R32F),s===r.HALF_FLOAT&&(l=r.R16F),s===r.UNSIGNED_BYTE&&(l=r.R8),s===r.UNSIGNED_SHORT&&(l=r.R16),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RED_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.R8UI),s===r.UNSIGNED_SHORT&&(l=r.R16UI),s===r.UNSIGNED_INT&&(l=r.R32UI),s===r.BYTE&&(l=r.R8I),s===r.SHORT&&(l=r.R16I),s===r.INT&&(l=r.R32I)),t===r.RG&&(s===r.FLOAT&&(l=r.RG32F),s===r.HALF_FLOAT&&(l=r.RG16F),s===r.UNSIGNED_BYTE&&(l=r.RG8),s===r.UNSIGNED_SHORT&&(l=r.RG16),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RG_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RG8UI),s===r.UNSIGNED_SHORT&&(l=r.RG16UI),s===r.UNSIGNED_INT&&(l=r.RG32UI),s===r.BYTE&&(l=r.RG8I),s===r.SHORT&&(l=r.RG16I),s===r.INT&&(l=r.RG32I)),t===r.RGB){const c=n?Qa:Ue.getTransfer(i);s===r.FLOAT&&(l=r.RGB32F),s===r.HALF_FLOAT&&(l=r.RGB16F),s===r.UNSIGNED_BYTE&&(l=r.RGB8),s===r.UNSIGNED_SHORT&&(l=r.RGB16),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I),s===r.UNSIGNED_BYTE&&(l=c===te?r.SRGB8:r.RGB8),s===r.UNSIGNED_SHORT_5_6_5&&(l=r.RGB565),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGB4),s===r.UNSIGNED_INT_5_9_9_9_REV&&(l=r.RGB9_E5)}if(t===r.RGB_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGB8UI),s===r.UNSIGNED_SHORT&&(l=r.RGB16UI),s===r.UNSIGNED_INT&&(l=r.RGB32UI),s===r.BYTE&&(l=r.RGB8I),s===r.SHORT&&(l=r.RGB16I),s===r.INT&&(l=r.RGB32I)),t===r.RGBA){const c=n?Qa:Ue.getTransfer(i);s===r.FLOAT&&(l=r.RGBA32F),s===r.HALF_FLOAT&&(l=r.RGBA16F),s===r.UNSIGNED_BYTE&&(l=r.RGBA8),s===r.UNSIGNED_SHORT&&(l=r.RGBA16),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I),s===r.UNSIGNED_BYTE&&(l=c===te?r.SRGB8_ALPHA8:r.RGBA8),s===r.UNSIGNED_SHORT_4_4_4_4&&(l=r.RGBA4),s===r.UNSIGNED_SHORT_5_5_5_1&&(l=r.RGB5_A1)}return t===r.RGBA_INTEGER&&(s===r.UNSIGNED_BYTE&&(l=r.RGBA8UI),s===r.UNSIGNED_SHORT&&(l=r.RGBA16UI),s===r.UNSIGNED_INT&&(l=r.RGBA32UI),s===r.BYTE&&(l=r.RGBA8I),s===r.SHORT&&(l=r.RGBA16I),s===r.INT&&(l=r.RGBA32I)),t===r.DEPTH_COMPONENT&&(s===r.UNSIGNED_SHORT&&(l=r.DEPTH_COMPONENT16),s===r.UNSIGNED_INT&&(l=r.DEPTH_COMPONENT24),s===r.FLOAT&&(l=r.DEPTH_COMPONENT32F)),t===r.DEPTH_STENCIL&&s===r.UNSIGNED_INT_24_8&&(l=r.DEPTH24_STENCIL8),(l===r.R16F||l===r.R32F||l===r.RG16F||l===r.RG32F||l===r.RGBA16F||l===r.RGBA32F)&&a.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:n}=this,r=Ue.getPrimaries(Ue.workingColorSpace),a=t.colorSpace===ri?null:Ue.getPrimaries(t.colorSpace),l=t.colorSpace===ri||r===a?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),s.texParameteri(e,s.TEXTURE_WRAP_S,ma[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,ma[t.wrapT]),(e===s.TEXTURE_3D||e===s.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,ma[t.wrapR])),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Wc[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,h=t.minFilter===Qt&&c?ei:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Wc[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Sf[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===ut||t.minFilter!==_o&&t.minFilter!==ei||t.type===Kt&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const u=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,u.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,n.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,n=this.getGLTextureType(e);let r=i[n];r===void 0&&(r=t.createTexture(),s.state.bindTexture(n,r),t.texParameteri(n,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(n,t.TEXTURE_MAG_FILTER,t.NEAREST),i[n]=r),s.set(e,{textureGPU:r,glTextureType:n,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:n,width:r,height:a,depth:l}=t,c=i.utils.convert(e.format,e.colorSpace),h=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,c,h,e.colorSpace,e.isVideoTexture),d=s.createTexture(),p=this.getGLTextureType(e);i.state.bindTexture(p,d),this.setTextureParameters(p,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,n,u,r,a,l):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,n,u,r,a,l):e.isVideoTexture||s.texStorage2D(p,n,u,r,a),i.set(e,{textureGPU:d,glTextureType:p,glFormat:c,glType:h,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:n,glTextureType:r,glFormat:a,glType:l}=i.get(t),{width:c,height:h}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(r,n),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(r,0,0,0,c,h,a,l,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:n}=t,{textureGPU:r,glTextureType:a,glFormat:l,glType:c,glInternalFormat:h}=this.backend.get(e);if(!(e.isRenderTargetTexture||r===void 0))if(this.backend.state.bindTexture(a,r),this.setTextureParameters(a,e),e.isCompressedTexture){const u=e.mipmaps,d=t.image;for(let p=0;p<u.length;p++){const f=u[p];e.isCompressedArrayTexture?e.format!==s.RGBA?l!==null?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,f.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,p,0,0,0,f.width,f.height,d.depth,l,c,f.data):l!==null?s.compressedTexSubImage2D(s.TEXTURE_2D,p,0,0,f.width,f.height,l,f.data):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const u=t.images;for(let d=0;d<6;d++){const p=vf(u[d]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,0,0,0,i,n,l,c,p)}}else if(e.isDataArrayTexture||e.isArrayTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isData3DTexture){const u=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,l,c,u.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,h,l,c,t.image);else{const u=vf(t.image);s.texSubImage2D(a,0,0,0,i,n,l,c,u)}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:n}=s.get(e);s.state.bindTexture(n,i),t.generateMipmap(n)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const n in i.framebuffers)t.deleteFramebuffer(i.framebuffers[n]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let n=0;n<i.msaaRenderbuffers.length;n++)t.deleteRenderbuffer(i.msaaRenderbuffers[n]);delete i.msaaRenderbuffers}}}destroyTexture(e){const{gl:t,backend:s}=this,{textureGPU:i,renderTarget:n}=s.get(e);this.deallocateRenderBuffers(n),t.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){const{gl:a,backend:l}=this,{state:c}=this.backend,{textureGPU:h,glTextureType:u,glType:d,glFormat:p}=l.get(t);c.bindTexture(u,h);let f,m,x,g,_,b,T,S,C;const w=e.isCompressedTexture?e.mipmaps[r]:e.image;if(s!==null)f=s.max.x-s.min.x,m=s.max.y-s.min.y,x=s.isBox3?s.max.z-s.min.z:1,g=s.min.x,_=s.min.y,b=s.isBox3?s.min.z:0;else{const X=Math.pow(2,-n);f=Math.floor(w.width*X),m=Math.floor(w.height*X),e.isDataArrayTexture||e.isArrayTexture?x=w.depth:e.isData3DTexture?x=Math.floor(w.depth*X):x=1,g=0,_=0,b=0}i!==null?(T=i.x,S=i.y,C=i.z):(T=0,S=0,C=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const R=a.getParameter(a.UNPACK_ROW_LENGTH),P=a.getParameter(a.UNPACK_IMAGE_HEIGHT),z=a.getParameter(a.UNPACK_SKIP_PIXELS),$=a.getParameter(a.UNPACK_SKIP_ROWS),q=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,w.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,g),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const j=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const X=l.get(e),Z=l.get(t),we=l.get(X.renderTarget),de=l.get(Z.renderTarget),ye=we.framebuffers[X.cacheKey],se=de.framebuffers[Z.cacheKey];c.bindFramebuffer(a.READ_FRAMEBUFFER,ye),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,se);let Me=a.COLOR_BUFFER_BIT;e.isDepthTexture&&(Me=a.DEPTH_BUFFER_BIT),a.blitFramebuffer(g,_,f,m,T,S,f,m,Me,a.NEAREST),c.bindFramebuffer(a.READ_FRAMEBUFFER,null),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else j?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,r,T,S,C,f,m,x,p,d,w.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,r,T,S,C,f,m,x,p,w.data):a.texSubImage3D(u,r,T,S,C,f,m,x,p,d,w):e.isDataTexture?a.texSubImage2D(u,r,T,S,f,m,p,d,w.data):e.isCompressedTexture?a.compressedTexSubImage2D(u,r,T,S,w.width,w.height,p,w.data):a.texSubImage2D(u,r,T,S,f,m,p,d,w);a.pixelStorei(a.UNPACK_ROW_LENGTH,R),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,P),a.pixelStorei(a.UNPACK_SKIP_PIXELS,z),a.pixelStorei(a.UNPACK_SKIP_ROWS,$),a.pixelStorei(a.UNPACK_SKIP_IMAGES,q),r===0&&t.generateMipmaps&&a.generateMipmap(u),c.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:n}=this.backend,{textureGPU:r}=this.backend.get(e),{x:a,y:l,z:c,w:h}=s,u=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const p=a!==0||l!==0;let f,m;if(e.isDepthTexture===!0?(f=i.DEPTH_BUFFER_BIT,m=i.DEPTH_ATTACHMENT,t.stencil&&(f|=i.STENCIL_BUFFER_BIT)):(f=i.COLOR_BUFFER_BIT,m=i.COLOR_ATTACHMENT0),p){const x=this.backend.get(t.renderTarget),g=x.framebuffers[t.getCacheKey()],_=x.msaaFrameBuffer;n.bindFramebuffer(i.DRAW_FRAMEBUFFER,g),n.bindFramebuffer(i.READ_FRAMEBUFFER,_);const b=d-l-h;i.blitFramebuffer(a,b,a+c,b+h,a,b,a+c,b+h,f,i.NEAREST),n.bindFramebuffer(i.READ_FRAMEBUFFER,g),n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,b,c,h),n.unbindTexture()}else{const x=i.createFramebuffer();n.bindFramebuffer(i.DRAW_FRAMEBUFFER,x),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,m,i.TEXTURE_2D,r,0),i.blitFramebuffer(0,0,c,h,0,0,c,h,f,i.NEAREST),i.deleteFramebuffer(x)}}else n.bindTexture(i.TEXTURE_2D,r),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,d-h-l,c,h),n.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:n}=this,r=t.renderTarget,{depthTexture:a,depthBuffer:l,stencilBuffer:c,width:h,height:u}=r;if(n.bindRenderbuffer(n.RENDERBUFFER,e),l&&!c){let d=n.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(n.RENDERBUFFER,r.samples,d,h,u):s>0?(a&&a.isDepthTexture&&a.type===n.FLOAT&&(d=n.DEPTH_COMPONENT32F),n.renderbufferStorageMultisample(n.RENDERBUFFER,s,d,h,u)):n.renderbufferStorage(n.RENDERBUFFER,d,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,e)}else l&&c&&(s>0?n.renderbufferStorageMultisample(n.RENDERBUFFER,s,n.DEPTH24_STENCIL8,h,u):n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_STENCIL,h,u),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,s,i,n,r){const{backend:a,gl:l}=this,{textureGPU:c,glFormat:h,glType:u}=this.backend.get(e),d=l.createFramebuffer();l.bindFramebuffer(l.READ_FRAMEBUFFER,d);const p=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+r:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,p,c,0);const f=this._getTypedArrayType(u),m=this._getBytesPerTexel(u,h),g=i*n*m,_=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.bufferData(l.PIXEL_PACK_BUFFER,g,l.STREAM_READ),l.readPixels(t,s,i,n,h,u,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const b=new f(g/f.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,_),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,b),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteFramebuffer(d),b}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;if(e===s.UNSIGNED_BYTE&&(i=1),(e===s.UNSIGNED_SHORT_4_4_4_4||e===s.UNSIGNED_SHORT_5_5_5_1||e===s.UNSIGNED_SHORT_5_6_5||e===s.UNSIGNED_SHORT||e===s.HALF_FLOAT)&&(i=2),(e===s.UNSIGNED_INT||e===s.FLOAT)&&(i=4),t===s.RGBA)return i*4;if(t===s.RGB)return i*3;if(t===s.ALPHA)return i}}function vf(o){return o.isDataTexture?o.image.data:typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas?o:o.data}class kA{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class zA{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const wf={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class GA{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:n,type:r,info:a,index:l}=this;l!==0?s.drawElements(i,t,r,e):s.drawArrays(i,e,t),a.update(n,t,1)}renderInstances(e,t,s){const{gl:i,mode:n,type:r,index:a,object:l,info:c}=this;s!==0&&(a!==0?i.drawElementsInstanced(n,t,r,e,s):i.drawArraysInstanced(n,e,t,s),c.update(l,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:n,object:r,info:a}=this;if(s===0)return;const l=i.get("WEBGL_multi_draw");if(l===null)for(let c=0;c<s;c++)this.render(e[c],t[c]);else{this.index!==0?l.multiDrawElementsWEBGL(n,t,0,this.type,e,0,s):l.multiDrawArraysWEBGL(n,e,0,t,0,s);let c=0;for(let h=0;h<s;h++)c+=t[h];a.update(r,c,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:n,mode:r,object:a,info:l}=this;if(s===0)return;const c=n.get("WEBGL_multi_draw");if(c===null)for(let h=0;h<s;h++)this.renderInstances(e[h],t[h],i[h]);else{this.index!==0?c.multiDrawElementsInstancedWEBGL(r,t,0,this.type,e,0,i,0,s):c.multiDrawArraysInstancedWEBGL(r,e,0,t,0,i,0,s);let h=0;for(let u=0;u<s;u++)h+=t[u]*i[u];l.update(a,h,1)}}}class zy{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class VA extends zy{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){console.warn("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return oi(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(t==null||this.activeQuery!==null)return;const s=this.queries[t];if(s)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){console.error("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(s){console.error("Error in endQuery:",s),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[i,n]of this.queryStates)if(n==="ended"){const r=this.queries[i];e.push(this.resolveQuery(r))}if(e.length===0)return this.lastValue;const s=(await Promise.all(e)).reduce((i,n)=>i+n,0);return this.lastValue=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,s}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let s,i=!1;const n=()=>{s&&(clearTimeout(s),s=null)},r=l=>{i||(i=!0,n(),t(l))},a=()=>{if(this.isDisposed){r(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){r(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){s=setTimeout(a,1);return}const h=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(h)/1e6)}catch(l){console.error("Error checking query:",l),t(this.lastValue)}};a()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}const Mf=new he;class Cf extends ky{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",s);function n(r){r.preventDefault();const a={api:"WebGL",message:r.statusMessage||"Unknown reason",reason:null,originalEvent:r};e.onDeviceLost(a)}this._onContextLost=n,e.domElement.addEventListener("webglcontextlost",n,!1),this.gl=i,this.extensions=new kA(this),this.capabilities=new zA(this),this.attributeUtils=new BA(this),this.textureUtils=new UA(this),this.bufferRenderer=new GA(this),this.state=new IA(this),this.utils=new LA(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return Ut}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),s!==null){const n=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:n}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e.autoAllocateDepthBuffer===!0&&e.multiview===!1&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e.autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new VA(this.gl,t,2048));const s=this.timestampQueryPool[t];s.allocateQueriesForContext(e)!==null&&s.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:n,height:r}=this.getDrawingBufferSize(Mf);t.viewport(0,0,n,r)}if(e.scissor){const{x:n,y:r,width:a,height:l}=e.scissorValue;t.scissor(n,e.height-l-r,a,l)}this.initTimestampQuery(e),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),n=i.previousContext;s.resetVertexState();const r=e.occlusionQueryCount;r>0&&(r>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(a!==null)for(let l=0;l<a.length;l++){const c=a[l];c.generateMipmaps&&this.generateMipmaps(c)}if(this._currentContext=n,e.textures!==null&&e.renderTarget){const l=this.get(e.renderTarget),{resolveDepthBuffer:c,samples:h}=e.renderTarget;if(h>0&&this._useMultisampledExtension(e.renderTarget)===!1){const u=l.framebuffers[e.getCacheKey()],d=t.COLOR_BUFFER_BIT,p=l.msaaFrameBuffer,f=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,p),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u);for(let m=0;m<f.length;m++)if(e.scissor){const{x,y:g,width:_,height:b}=e.scissorValue,T=e.height-b-g;t.blitFramebuffer(x,T,x+_,T+b,x,T,x+_,T+b,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateSubFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray,x,T,_,b)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,d,t.NEAREST),this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,l.invalidationArray)}else if(c===!1&&l.framebuffers){const u=l.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,u),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,l.depthInvalidationArray)}}if(n!==null)if(this._setFramebuffer(n),n.viewport)this.updateViewport(n);else{const{width:l,height:c}=this.getDrawingBufferSize(Mf);s.viewport(0,0,l,c)}this.prepareTimestampBuffer(e)}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const a=()=>{let l=0;for(let c=0;c<s.length;c++){const h=s[c];h!==null&&r.getQueryParameter(h,r.QUERY_RESULT_AVAILABLE)&&(r.getQueryParameter(h,r.QUERY_RESULT)===0&&n.add(i[c]),s[c]=null,r.deleteQuery(h),l++)}l<s.length?requestAnimationFrame(a):t.occluded=n};a()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:n,height:r}=e.viewportValue;t.viewport(s,e.height-r-i,n,r)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,n=!0){const{gl:r,renderer:a}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let l=0;if(e&&(l|=r.COLOR_BUFFER_BIT),t&&(l|=r.DEPTH_BUFFER_BIT),s&&(l|=r.STENCIL_BUFFER_BIT),l!==0){let c;i.clearColorValue?c=i.clearColorValue:c=this.getClearColor();const h=a.getClearDepth(),u=a.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)r.clearColor(c.r,c.g,c.b,c.a),r.clear(l);else{if(n&&this._setFramebuffer(i),e)for(let d=0;d<i.textures.length;d++)d===0?r.clearBufferfv(r.COLOR,d,[c.r,c.g,c.b,c.a]):r.clearBufferfv(r.COLOR,d,[0,0,0,1]);t&&s?r.clearBufferfi(r.DEPTH_STENCIL,0,h,u):t?r.clearBufferfv(r.DEPTH,0,[h]):s&&r.clearBufferiv(r.STENCIL,0,[u])}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,s,i){const{state:n,gl:r}=this;this.discard===!1&&(r.enable(r.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:l,attributes:c}=this.get(i),h=this._getVaoKey(c),u=this.vaoCache[h];u===void 0?this._createVao(c):n.setVertexState(u),n.useProgram(a),this._bindUniforms(s);const d=this._getTransformFeedback(l);r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,d),r.beginTransformFeedback(r.POINTS),c[0].isStorageInstancedBufferAttribute?r.drawArraysInstanced(r.POINTS,0,1,t.count):r.drawArrays(r.POINTS,0,t.count),r.endTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null);for(let p=0;p<l.length;p++){const f=l[p];f.pbo&&this.textureUtils.copyBufferToTexture(f.transformBuffer,f.pbo),f.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:n,hardwareClippingPlanes:r}=e,{programGPU:a}=this.get(s),{gl:l,state:c}=this,h=this.get(n),u=e.getDrawParameters();if(u===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinant()<0;c.setMaterial(i,d,r),c.useProgram(a);const p=this.get(e);let f=p.staticVao;if(f===void 0||p.geometryId!==e.geometry.id){const w=this._getVaoKey(e.getAttributes());if(f=this.vaoCache[w],f===void 0){let R;({vaoGPU:f,staticVao:R}=this._createVao(e.getAttributes())),R&&(p.staticVao=f,p.geometryId=e.geometry.id)}}const m=e.getIndex(),x=m!==null?this.get(m).bufferGPU:null;c.setVertexState(f,x);const g=h.lastOcclusionObject;if(g!==t&&g!==void 0){if(g!==null&&g.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),t.occlusionTest===!0){const w=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,w),h.occlusionQueries[h.occlusionQueryIndex]=w,h.occlusionQueryObjects[h.occlusionQueryIndex]=t}h.lastOcclusionObject=t}const _=this.bufferRenderer;t.isPoints?_.mode=l.POINTS:t.isLineSegments?_.mode=l.LINES:t.isLine?_.mode=l.LINE_STRIP:t.isLineLoop?_.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),_.mode=l.LINES):_.mode=l.TRIANGLES;const{vertexCount:b,instanceCount:T}=u;let{firstVertex:S}=u;if(_.object=t,m!==null){S*=m.array.BYTES_PER_ELEMENT;const w=this.get(m);_.index=m.count,_.type=w.type}else _.index=0;const C=()=>{t.isBatchedMesh?t._multiDrawInstances!==null?(oi("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?_.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):oi("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?_.renderInstances(S,b,T):_.render(S,b)};if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const w=this.get(e.camera),R=e.camera.cameras,P=e.getBindingGroup("cameraIndex").bindings[0];if(w.indexesGPU===void 0||w.indexesGPU.length!==R.length){const Z=new Uint32Array([0,0,0,0]),we=[];for(let de=0,ye=R.length;de<ye;de++){const se=l.createBuffer();Z[0]=de,l.bindBuffer(l.UNIFORM_BUFFER,se),l.bufferData(l.UNIFORM_BUFFER,Z,l.STATIC_DRAW),we.push(se)}w.indexesGPU=we}const z=this.get(P),$=this.renderer.getPixelRatio(),q=this._currentContext.renderTarget,j=this._isRenderCameraDepthArray(this._currentContext),X=this._currentContext.activeCubeFace;if(j){const Z=this.get(q.depthTexture);if(Z.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){Z.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:we}=q;for(let de=0,ye=R.length;de<ye;de++)this.renderer._activeCubeFace=de,this._currentContext.activeCubeFace=de,this._setFramebuffer(this._currentContext),this.clear(!1,!0,we,this._currentContext,!1);this.renderer._activeCubeFace=X,this._currentContext.activeCubeFace=X}}for(let Z=0,we=R.length;Z<we;Z++){const de=R[Z];if(t.layers.test(de.layers)){j&&(this.renderer._activeCubeFace=Z,this._currentContext.activeCubeFace=Z,this._setFramebuffer(this._currentContext));const ye=de.viewport;if(ye!==void 0){const se=ye.x*$,Me=ye.y*$,ze=ye.width*$,ot=ye.height*$;c.viewport(Math.floor(se),Math.floor(e.context.height-ot-Me),Math.floor(ze),Math.floor(ot))}c.bindBufferBase(l.UNIFORM_BUFFER,z.index,w.indexesGPU[Z]),C()}this._currentContext.activeCubeFace=X,this.renderer._activeCubeFace=X}}else C()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new FA(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,n=s==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(n,i),t.compileShader(n),this.set(e,{shaderGPU:n})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:n,vertexProgram:r}=i,a=s.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).shaderGPU;if(s.attachShader(a,l),s.attachShader(a,c),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:l,vertexShader:c}),t!==null&&this.parallel){const h=new Promise(u=>{const d=this.parallel,p=()=>{s.getProgramParameter(a,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),u()):requestAnimationFrame(p)};p()});t.push(h);return}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split(`
|
|
255
255
|
`),i=[],n=Math.max(t-6,0),r=Math.min(t+6,s.length);for(let a=n;a<r;a++){const l=a+1;i.push(`${l===t?">":" "} ${l}: ${s[a]}`)}return i.join(`
|
|
256
256
|
`)}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),n=e.getShaderInfoLog(t).trim();if(i&&n==="")return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const a=parseInt(r[1]);return s.toUpperCase()+`
|
|
257
257
|
|
|
@@ -263,7 +263,7 @@ Program Info Log: `+n+`
|
|
|
263
263
|
`+r+`
|
|
264
264
|
`+a)}else n!==""&&console.warn("THREE.WebGLProgram: Program Info Log:",n)}}_completeCompile(e,t){const{state:s,gl:i}=this,n=this.get(t),{programGPU:r,fragmentShader:a,vertexShader:l}=n;i.getProgramParameter(r,i.LINK_STATUS)===!1&&this._logProgramError(r,a,l),s.useProgram(r);const c=e.getBindings();this._setupBindings(c,r),this.set(t,{programGPU:r})}createComputePipeline(e,t){const{state:s,gl:i}=this,n={stage:"fragment",code:`#version 300 es
|
|
265
265
|
precision highp float;
|
|
266
|
-
void main() {}`};this.createProgram(n);const{computeProgram:r}=e,a=i.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).shaderGPU,h=r.transforms,u=[],d=[];for(let y=0;y<h.length;y++){const g=h[y];u.push(g.varyingName),d.push(g.attributeNode)}i.attachShader(a,l),i.attachShader(a,c),i.transformFeedbackVaryings(a,u,i.SEPARATE_ATTRIBS),i.linkProgram(a),i.getProgramParameter(a,i.LINK_STATUS)===!1&&this._logProgramError(a,l,c),s.useProgram(a),this._setupBindings(t,a);const p=r.attributes,f=[],m=[];for(let y=0;y<p.length;y++){const g=p[y].node.attribute;f.push(g),this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER)}for(let y=0;y<d.length;y++){const g=d[y].attribute;this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER);const _=this.get(g);m.push(_)}this.set(e,{programGPU:a,transformBuffers:m,attributes:f})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let s=0,i=0;for(const n of t){this.set(n,{textures:i,uniformBuffers:s});for(const r of n.bindings)r.isUniformBuffer&&s++,r.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,n=s.textures;for(const r of e.bindings)if(r.isUniformsGroup||r.isUniformBuffer){const a=r.buffer,l=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,a,t.DYNAMIC_DRAW),this.set(r,{index:i++,bufferGPU:l})}else if(r.isSampledTexture){const{textureGPU:a,glTextureType:l}=this.get(r.texture);this.set(r,{index:n++,textureGPU:a,glTextureType:l})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,n=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW)}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(Tf).filter(i=>Tf[i]===e),s=this.extensions;for(let i=0;i<t.length;i++)if(s.has(t[i]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){this.textureUtils.copyTextureToTexture(e,t,s,i,n,r)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(e.textures!==null){const n=e.renderTarget,r=this.get(n),{samples:a,depthBuffer:l,stencilBuffer:c}=n,h=n.isWebGLCubeRenderTarget===!0,u=n.isRenderTarget3D===!0,d=n.depth>1,p=n.isXRRenderTarget===!0,f=p===!0&&n.hasExternalTextures===!0;let m=r.msaaFrameBuffer,y=r.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(n),T=Jm(e);let S;if(h?(r.cubeFramebuffers||(r.cubeFramebuffers={}),S=r.cubeFramebuffers[T]):p&&f===!1?S=this._xrFramebuffer:(r.framebuffers||(r.framebuffers={}),S=r.framebuffers[T]),S===void 0){S=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,S);const C=e.textures,w=[];if(h){r.cubeFramebuffers[T]=S;const{textureGPU:P}=this.get(C[0]),z=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+z,P,0)}else{r.framebuffers[T]=S;for(let P=0;P<C.length;P++){const z=C[P],$=this.get(z);$.renderTarget=e.renderTarget,$.cacheKey=T;const q=t.COLOR_ATTACHMENT0+P;if(n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,q,$.textureGPU,0,a,0,2);else if(u||d){const j=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,q,$.textureGPU,0,j)}else b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0)}s.drawBuffers(e,S)}const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(P,e,0,b),r.xrDepthRenderbuffer=P,w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else if(e.depthTexture!==null){w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const P=this.get(e.depthTexture);if(P.renderTarget=e.renderTarget,P.cacheKey=T,n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,a,0,2);else if(f&&b)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const z=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,R,P.textureGPU,0,z)}else t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}r.depthInvalidationArray=w}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,S);const w=this.renderer._activeCubeFace,R=this.get(e.depthTexture),P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,P,R.textureGPU,0,w)}if(p||b||n.multiview){s.bindFramebuffer(t.FRAMEBUFFER,S);const w=this.get(e.textures[0]);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,w.textureGPU,0,a,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0);const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=r.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else{const P=this.get(e.depthTexture);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,a,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}}}if(a>0&&b===!1&&!n.multiview){if(m===void 0){const C=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const w=[],R=e.textures;for(let P=0;P<R.length;P++){if(w[P]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,w[P]),C.push(t.COLOR_ATTACHMENT0+P),l){const q=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;C.push(q)}const z=e.textures[P],$=this.get(z);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,$.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+P,t.RENDERBUFFER,w[P])}if(r.msaaFrameBuffer=m,r.msaaRenderbuffers=w,y===void 0){y=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(y,e,a),r.depthRenderbuffer=y;const P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;C.push(P)}r.invalidationArray=C}i=r.msaaFrameBuffer}else i=S}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){const i=this.get(e[s]);t+=":"+i.id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();let i="",n=!0;t.bindVertexArray(s);for(let r=0;r<e.length;r++){const a=e[r],l=this.get(a);i+=":"+l.id,t.bindBuffer(t.ARRAY_BUFFER,l.bufferGPU),t.enableVertexAttribArray(r),(a.isStorageBufferAttribute||a.isStorageInstancedBufferAttribute)&&(n=!1);let c,h;a.isInterleavedBufferAttribute===!0?(c=a.data.stride*l.bytesPerElement,h=a.offset*l.bytesPerElement):(c=0,h=0),l.isInteger?t.vertexAttribIPointer(r,a.itemSize,l.type,c,h):t.vertexAttribPointer(r,a.itemSize,l.type,a.normalized,c,h),a.isInstancedBufferAttribute&&!a.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,a.meshPerAttribute):a.isInterleavedBufferAttribute&&a.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,a.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),this.vaoCache[i]=s,{vaoGPU:s,staticVao:n}}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let s=this.transformFeedbackCache[t];if(s!==void 0)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let n=0;n<e.length;n++){const r=e[n];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,n,r.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const n of i.bindings){const a=this.get(n).index;if(n.isUniformsGroup||n.isUniformBuffer){const l=s.getUniformBlockIndex(t,n.name);s.uniformBlockBinding(t,l,a)}else if(n.isSampledTexture){const l=s.getUniformLocation(t,n.name);s.uniform1i(l,a)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const n of i.bindings){const r=this.get(n),a=r.index;n.isUniformsGroup||n.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,a,r.bufferGPU):n.isSampledTexture&&s.bindTexture(r.glTextureType,r.textureGPU,t.TEXTURE0+a)}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e.autoAllocateDepthBuffer!==!1}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Zn={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list",TriangleStrip:"triangle-strip"},gt={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},Ct={Store:"store"},Ce={Load:"load",Clear:"clear"},Gc={CCW:"ccw"},Hc={None:"none",Front:"front",Back:"back"},mr={Uint16:"uint16",Uint32:"uint32"},M={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},Wc={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},ln={Linear:"linear",Nearest:"nearest"},ie={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},qi={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},wf={None:0,All:15},_i={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},$c={Storage:"storage",ReadOnlyStorage:"read-only-storage"},jc={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},Mf={NonFiltering:"non-filtering",Comparison:"comparison"},Yi={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},Cf={TwoD:"2d",ThreeD:"3d"},ft={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},_A={All:"all"},ma={Vertex:"vertex",Instance:"instance"},$h={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class bA extends Zu{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class TA extends bA{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class SA extends Ry{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let vA=0;class wA extends SA{constructor(e,t){super("StorageBuffer_"+vA++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Zs.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class MA extends Li{constructor(e){super(),this.device=e;const t=`
|
|
266
|
+
void main() {}`};this.createProgram(n);const{computeProgram:r}=e,a=i.createProgram(),l=this.get(n).shaderGPU,c=this.get(r).shaderGPU,h=r.transforms,u=[],d=[];for(let x=0;x<h.length;x++){const g=h[x];u.push(g.varyingName),d.push(g.attributeNode)}i.attachShader(a,l),i.attachShader(a,c),i.transformFeedbackVaryings(a,u,i.SEPARATE_ATTRIBS),i.linkProgram(a),i.getProgramParameter(a,i.LINK_STATUS)===!1&&this._logProgramError(a,l,c),s.useProgram(a),this._setupBindings(t,a);const p=r.attributes,f=[],m=[];for(let x=0;x<p.length;x++){const g=p[x].node.attribute;f.push(g),this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER)}for(let x=0;x<d.length;x++){const g=d[x].attribute;this.has(g)||this.attributeUtils.createAttribute(g,i.ARRAY_BUFFER);const _=this.get(g);m.push(_)}this.set(e,{programGPU:a,transformBuffers:m,attributes:f})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let s=0,i=0;for(const n of t){this.set(n,{textures:i,uniformBuffers:s});for(const r of n.bindings)r.isUniformBuffer&&s++,r.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,n=s.textures;for(const r of e.bindings)if(r.isUniformsGroup||r.isUniformBuffer){const a=r.buffer,l=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,l),t.bufferData(t.UNIFORM_BUFFER,a,t.DYNAMIC_DRAW),this.set(r,{index:i++,bufferGPU:l})}else if(r.isSampledTexture){const{textureGPU:a,glTextureType:l}=this.get(r.texture);this.set(r,{index:n++,textureGPU:a,glTextureType:l})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,n=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,n,t.DYNAMIC_DRAW)}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(wf).filter(i=>wf[i]===e),s=this.extensions;for(let i=0;i<t.length;i++)if(s.has(t[i]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){this.textureUtils.copyTextureToTexture(e,t,s,i,n,r)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(e.textures!==null){const n=e.renderTarget,r=this.get(n),{samples:a,depthBuffer:l,stencilBuffer:c}=n,h=n.isWebGLCubeRenderTarget===!0,u=n.isRenderTarget3D===!0,d=n.depth>1,p=n.isXRRenderTarget===!0,f=p===!0&&n.hasExternalTextures===!0;let m=r.msaaFrameBuffer,x=r.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(n),T=ig(e);let S;if(h?(r.cubeFramebuffers||(r.cubeFramebuffers={}),S=r.cubeFramebuffers[T]):p&&f===!1?S=this._xrFramebuffer:(r.framebuffers||(r.framebuffers={}),S=r.framebuffers[T]),S===void 0){S=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,S);const C=e.textures,w=[];if(h){r.cubeFramebuffers[T]=S;const{textureGPU:P}=this.get(C[0]),z=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+z,P,0)}else{r.framebuffers[T]=S;for(let P=0;P<C.length;P++){const z=C[P],$=this.get(z);$.renderTarget=e.renderTarget,$.cacheKey=T;const q=t.COLOR_ATTACHMENT0+P;if(n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,q,$.textureGPU,0,a,0,2);else if(u||d){const j=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,q,$.textureGPU,0,j)}else b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,q,t.TEXTURE_2D,$.textureGPU,0)}s.drawBuffers(e,S)}const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(P,e,0,b),r.xrDepthRenderbuffer=P,w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else if(e.depthTexture!==null){w.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const P=this.get(e.depthTexture);if(P.renderTarget=e.renderTarget,P.cacheKey=T,n.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,a,0,2);else if(f&&b)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const z=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,R,P.textureGPU,0,z)}else t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}r.depthInvalidationArray=w}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,S);const w=this.renderer._activeCubeFace,R=this.get(e.depthTexture),P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,P,R.textureGPU,0,w)}if(p||b||n.multiview){s.bindFramebuffer(t.FRAMEBUFFER,S);const w=this.get(e.textures[0]);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,w.textureGPU,0,a,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0);const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(n.autoAllocateDepthBuffer===!0){const P=r.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,P),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,P)}else{const P=this.get(e.depthTexture);n.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,P.textureGPU,0,a,0,2):b?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,P.textureGPU,0)}}}if(a>0&&b===!1&&!n.multiview){if(m===void 0){const C=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const w=[],R=e.textures;for(let P=0;P<R.length;P++){if(w[P]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,w[P]),C.push(t.COLOR_ATTACHMENT0+P),l){const q=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;C.push(q)}const z=e.textures[P],$=this.get(z);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,$.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+P,t.RENDERBUFFER,w[P])}if(r.msaaFrameBuffer=m,r.msaaRenderbuffers=w,x===void 0){x=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(x,e,a),r.depthRenderbuffer=x;const P=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;C.push(P)}r.invalidationArray=C}i=r.msaaFrameBuffer}else i=S}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){const i=this.get(e[s]);t+=":"+i.id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();let i="",n=!0;t.bindVertexArray(s);for(let r=0;r<e.length;r++){const a=e[r],l=this.get(a);i+=":"+l.id,t.bindBuffer(t.ARRAY_BUFFER,l.bufferGPU),t.enableVertexAttribArray(r),(a.isStorageBufferAttribute||a.isStorageInstancedBufferAttribute)&&(n=!1);let c,h;a.isInterleavedBufferAttribute===!0?(c=a.data.stride*l.bytesPerElement,h=a.offset*l.bytesPerElement):(c=0,h=0),l.isInteger?t.vertexAttribIPointer(r,a.itemSize,l.type,c,h):t.vertexAttribPointer(r,a.itemSize,l.type,a.normalized,c,h),a.isInstancedBufferAttribute&&!a.isInterleavedBufferAttribute?t.vertexAttribDivisor(r,a.meshPerAttribute):a.isInterleavedBufferAttribute&&a.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(r,a.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),this.vaoCache[i]=s,{vaoGPU:s,staticVao:n}}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let s=this.transformFeedbackCache[t];if(s!==void 0)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let n=0;n<e.length;n++){const r=e[n];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,n,r.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const n of i.bindings){const a=this.get(n).index;if(n.isUniformsGroup||n.isUniformBuffer){const l=s.getUniformBlockIndex(t,n.name);s.uniformBlockBinding(t,l,a)}else if(n.isSampledTexture){const l=s.getUniformLocation(t,n.name);s.uniform1i(l,a)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const n of i.bindings){const r=this.get(n),a=r.index;n.isUniformsGroup||n.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,a,r.bufferGPU):n.isSampledTexture&&s.bindTexture(r.glTextureType,r.textureGPU,t.TEXTURE0+a)}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e.autoAllocateDepthBuffer!==!1}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Kn={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list",TriangleStrip:"triangle-strip"},gt={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},Ct={Store:"store"},Ce={Load:"load",Clear:"clear"},$c={CCW:"ccw"},jc={None:"none",Front:"front",Back:"back"},yr={Uint16:"uint16",Uint32:"uint32"},M={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},qc={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},ln={Linear:"linear",Nearest:"nearest"},ie={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},qi={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},Ef={None:0,All:15},_i={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Yc={Storage:"storage",ReadOnlyStorage:"read-only-storage"},Xc={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},Af={NonFiltering:"non-filtering",Comparison:"comparison"},Yi={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},Rf={TwoD:"2d",ThreeD:"3d"},ft={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},HA={All:"all"},ga={Vertex:"vertex",Instance:"instance"},qh={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class WA extends Qu{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class $A extends WA{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class jA extends Dy{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let qA=0;class YA extends jA{constructor(e,t){super("StorageBuffer_"+qA++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Zs.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class XA extends Li{constructor(e){super(),this.device=e;const t=`
|
|
267
267
|
struct VarysStruct {
|
|
268
268
|
@builtin( position ) Position: vec4<f32>,
|
|
269
269
|
@location( 0 ) vTex : vec2<f32>
|
|
@@ -320,7 +320,7 @@ fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
|
|
|
320
320
|
return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
|
|
321
321
|
|
|
322
322
|
}
|
|
323
|
-
`;this.mipmapSampler=e.createSampler({minFilter:ln.Linear}),this.flipYSampler=e.createSampler({minFilter:ln.Nearest}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:t}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:s}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:i})}getTransferPipeline(e){let t=this.transferPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Zn.TriangleStrip,stripIndexFormat:mr.Uint32},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Zn.TriangleStrip,stripIndexFormat:mr.Uint32},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:n,height:r}=t.size,a=this.getTransferPipeline(i),l=this.getFlipYPipeline(i),c=this.device.createTexture({size:{width:n,height:r,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s}),u=c.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:0}),d=this.device.createCommandEncoder({}),p=(f,m,y)=>{const g=f.getBindGroupLayout(0),_=this.device.createBindGroup({layout:g,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:m}]}),b=d.beginRenderPass({colorAttachments:[{view:y,loadOp:Ce.Clear,storeOp:Ct.Store,clearValue:[0,0,0,0]}]});b.setPipeline(f),b.setBindGroup(0,_),b.draw(4,1,0,0),b.end()};p(a,h,u),p(l,u,h),this.device.queue.submit([d.finish()]),c.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);i.useCount===void 0&&(i.useCount=0,i.layers=[]);const n=i.layers[s]||this._mipmapCreateBundles(e,t,s),r=this.device.createCommandEncoder({});this._mipmapRunBundles(r,n),this.device.queue.submit([r.finish()]),i.useCount!==0&&(i.layers[s]=n),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),n=i.getBindGroupLayout(0);let r=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s});const a=[];for(let l=1;l<t.mipLevelCount;l++){const c=this.device.createBindGroup({layout:n,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:r}]}),h=e.createView({baseMipLevel:l,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:Ce.Clear,storeOp:Ct.Store,clearValue:[0,0,0,0]}]},d=this.device.createRenderBundleEncoder({colorFormats:[t.format]});d.setPipeline(i),d.setBindGroup(0,c),d.draw(4,1,0,0),a.push({renderBundles:[d.finish()],passDescriptor:u}),r=h}return a}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const n=t[i],r=e.beginRenderPass(n.passDescriptor);r.executeBundles(n.renderBundles),r.end()}}}const CA={[Im]:"never",[au]:"less",[Lm]:"equal",[Um]:"less-equal",[km]:"greater",[Vm]:"greater-equal",[Gm]:"always",[zm]:"not-equal"},EA=[0,1,3,2,4,5];class AA{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new Is,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,s=t.device,i=t.get(e),n={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};n.magFilter===ln.Linear&&n.minFilter===ln.Linear&&n.mipmapFilter===ln.Linear&&(n.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&(n.compare=CA[e.compareFunction]),i.sampler=s.createSampler(n)}createDefaultTexture(e){let t;const s=jh(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:n,height:r,depth:a,levels:l}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const c=this._getDimension(e),h=e.internalFormat||t.format||jh(e,s.device);i.format=h;const{samples:u,primarySamples:d,isMSAA:p}=s.utils.getTextureSampleData(e);let f=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(f|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:n,height:r,depthOrArrayLayers:a},mipLevelCount:l,sampleCount:d,dimension:c,format:h,usage:f};if(e.isVideoTexture){const y=e.source.data,g=new VideoFrame(y);m.size.width=g.displayWidth,m.size.height=g.displayHeight,g.close(),i.externalTexture=y}else{if(h===void 0){console.warn("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(m.textureBindingViewDimension=ft.Cube),i.texture=s.device.createTexture(m)}if(p){const y=Object.assign({},m);y.label=y.label+"-msaa",y.sampleCount=u,i.msaaTexture=s.device.createTexture(y)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture!==void 0&&s.texture.destroy(),s.msaaTexture!==void 0&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){const s=this.backend.get(e);delete s.sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let s=0;s<6;s++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,s);else{const s=e.image.depth||1;for(let i=0;i<s;i++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,i)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const s=this.backend,{width:i,height:n}=s.getDrawingBufferSize(),r=this.depthTexture,a=s.get(r).texture;let l,c;if(t?(l=ti,c=Fi):e&&(l=Bs,c=Xe),a!==void 0){if(r.image.width===i&&r.image.height===n&&r.format===l&&r.type===c)return a;this.destroyTexture(r)}return r.name="depthBuffer",r.format=l,r.type=c,r.image.width=i,r.image.height=n,this.createTexture(r,{width:i,height:n}),s.get(r).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:i}=s;if(!(e.isRenderTargetTexture||i===void 0)){if(e.isDataTexture)this._copyBufferToTexture(t.image,s.texture,i,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let n=0;n<t.image.depth;n++)this._copyBufferToTexture(t.image,s.texture,i,n,e.flipY,n);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,s.texture,i,e.flipY,e.premultiplyAlpha);else if(e.isVideoTexture){const n=e.source.data;s.externalTexture=n}else this._copyImageToTexture(t.image,s.texture,i,0,e.flipY,e.premultiplyAlpha);s.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,s,i,n,r){const a=this.backend.device,l=this.backend.get(e),c=l.texture,h=l.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let d=i*u;d=Math.ceil(d/256)*256;const p=a.createBuffer({size:i*n*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),f=a.createCommandEncoder();f.copyTextureToBuffer({texture:c,origin:{x:t,y:s,z:r}},{buffer:p,bytesPerRow:d},{width:i,height:n});const m=this._getTypedArrayType(h);a.queue.submit([f.finish()]),await p.mapAsync(GPUMapMode.READ);const y=p.getMappedRange();return new m(y)}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new St;s.minFilter=ut,s.magFilter=ut,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new vl;s.minFilter=ut,s.magFilter=ut,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(e===null){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,s,i,n){for(let r=0;r<6;r++){const a=e[r],l=i===!0?EA[r]:r;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,l,i):this._copyImageToTexture(a,t,s,l,i,n)}}_copyImageToTexture(e,t,s,i,n,r){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:n},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i},premultipliedAlpha:r},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new MA(this.backend.device)),e}_generateMipmaps(e,t,s=0){this._getPassUtils().generateMipmaps(e,t,s)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,n,r=0){const a=this.backend.device,l=e.data,c=this._getBytesPerTexel(s.format),h=e.width*c;a.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*c*r,bytesPerRow:h},{width:e.width,height:e.height,depthOrArrayLayers:1}),n===!0&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,n=this._getBlockData(s.format),r=s.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const l=e[a],c=l.width,h=l.height,u=r?s.size.depthOrArrayLayers:1,d=Math.ceil(c/n.width)*n.byteLength,p=d*Math.ceil(h/n.height);for(let f=0;f<u;f++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:f}},l.data,{offset:f*p,bytesPerRow:d,rowsPerImage:Math.ceil(h/n.height)},{width:Math.ceil(c/n.width)*n.width,height:Math.ceil(h/n.height)*n.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===M.BC1RGBAUnorm||e===M.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.BC2RGBAUnorm||e===M.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.BC3RGBAUnorm||e===M.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.BC4RUnorm||e===M.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===M.BC5RGUnorm||e===M.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===M.BC6HRGBUFloat||e===M.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===M.BC7RGBAUnorm||e===M.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.ETC2RGB8Unorm||e===M.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.ETC2RGB8A1Unorm||e===M.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.ETC2RGBA8Unorm||e===M.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===M.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===M.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===M.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===M.ASTC4x4Unorm||e===M.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.ASTC5x4Unorm||e===M.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===M.ASTC5x5Unorm||e===M.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===M.ASTC6x5Unorm||e===M.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===M.ASTC6x6Unorm||e===M.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===M.ASTC8x5Unorm||e===M.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===M.ASTC8x6Unorm||e===M.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===M.ASTC8x8Unorm||e===M.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===M.ASTC10x5Unorm||e===M.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===M.ASTC10x6Unorm||e===M.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===M.ASTC10x8Unorm||e===M.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===M.ASTC10x10Unorm||e===M.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===M.ASTC12x10Unorm||e===M.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===M.ASTC12x12Unorm||e===M.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=Wc.ClampToEdge;return e===cr?t=Wc.Repeat:e===hr&&(t=Wc.MirrorRepeat),t}_convertFilterMode(e){let t=ln.Linear;return(e===ut||e===Om||e===xo)&&(t=ln.Nearest),t}_getBytesPerTexel(e){if(e===M.R8Unorm||e===M.R8Snorm||e===M.R8Uint||e===M.R8Sint)return 1;if(e===M.R16Uint||e===M.R16Sint||e===M.R16Float||e===M.RG8Unorm||e===M.RG8Snorm||e===M.RG8Uint||e===M.RG8Sint)return 2;if(e===M.R32Uint||e===M.R32Sint||e===M.R32Float||e===M.RG16Uint||e===M.RG16Sint||e===M.RG16Float||e===M.RGBA8Unorm||e===M.RGBA8UnormSRGB||e===M.RGBA8Snorm||e===M.RGBA8Uint||e===M.RGBA8Sint||e===M.BGRA8Unorm||e===M.BGRA8UnormSRGB||e===M.RGB9E5UFloat||e===M.RGB10A2Unorm||e===M.RG11B10UFloat||e===M.Depth32Float||e===M.Depth24Plus||e===M.Depth24PlusStencil8||e===M.Depth32FloatStencil8)return 4;if(e===M.RG32Uint||e===M.RG32Sint||e===M.RG32Float||e===M.RGBA16Uint||e===M.RGBA16Sint||e===M.RGBA16Float)return 8;if(e===M.RGBA32Uint||e===M.RGBA32Sint||e===M.RGBA32Float)return 16}_getTypedArrayType(e){if(e===M.R8Uint)return Uint8Array;if(e===M.R8Sint)return Int8Array;if(e===M.R8Unorm)return Uint8Array;if(e===M.R8Snorm)return Int8Array;if(e===M.RG8Uint)return Uint8Array;if(e===M.RG8Sint)return Int8Array;if(e===M.RG8Unorm)return Uint8Array;if(e===M.RG8Snorm)return Int8Array;if(e===M.RGBA8Uint)return Uint8Array;if(e===M.RGBA8Sint)return Int8Array;if(e===M.RGBA8Unorm)return Uint8Array;if(e===M.RGBA8Snorm)return Int8Array;if(e===M.R16Uint)return Uint16Array;if(e===M.R16Sint)return Int16Array;if(e===M.RG16Uint)return Uint16Array;if(e===M.RG16Sint)return Int16Array;if(e===M.RGBA16Uint)return Uint16Array;if(e===M.RGBA16Sint)return Int16Array;if(e===M.R16Float||e===M.RG16Float||e===M.RGBA16Float)return Uint16Array;if(e===M.R32Uint)return Uint32Array;if(e===M.R32Sint)return Int32Array;if(e===M.R32Float)return Float32Array;if(e===M.RG32Uint)return Uint32Array;if(e===M.RG32Sint)return Int32Array;if(e===M.RG32Float)return Float32Array;if(e===M.RGBA32Uint)return Uint32Array;if(e===M.RGBA32Sint)return Int32Array;if(e===M.RGBA32Float)return Float32Array;if(e===M.BGRA8Unorm||e===M.BGRA8UnormSRGB)return Uint8Array;if(e===M.RGB10A2Unorm||e===M.RGB9E5UFloat||e===M.RG11B10UFloat)return Uint32Array;if(e===M.Depth32Float)return Float32Array;if(e===M.Depth24Plus||e===M.Depth24PlusStencil8)return Uint32Array;if(e===M.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.isData3DTexture?t=Cf.ThreeD:t=Cf.TwoD,t}}function jh(o,e=null){const t=o.format,s=o.type,i=o.colorSpace,n=Ue.getTransfer(i);let r;if(o.isCompressedTexture===!0||o.isCompressedArrayTexture===!0)switch(t){case Ra:r=n===te?M.BC1RGBAUnormSRGB:M.BC1RGBAUnorm;break;case Na:r=n===te?M.BC2RGBAUnormSRGB:M.BC2RGBAUnorm;break;case Pa:r=n===te?M.BC3RGBAUnormSRGB:M.BC3RGBAUnorm;break;case gh:r=n===te?M.ETC2RGB8UnormSRGB:M.ETC2RGB8Unorm;break;case yh:r=n===te?M.ETC2RGBA8UnormSRGB:M.ETC2RGBA8Unorm;break;case xh:r=n===te?M.ASTC4x4UnormSRGB:M.ASTC4x4Unorm;break;case _h:r=n===te?M.ASTC5x4UnormSRGB:M.ASTC5x4Unorm;break;case bh:r=n===te?M.ASTC5x5UnormSRGB:M.ASTC5x5Unorm;break;case Th:r=n===te?M.ASTC6x5UnormSRGB:M.ASTC6x5Unorm;break;case Sh:r=n===te?M.ASTC6x6UnormSRGB:M.ASTC6x6Unorm;break;case vh:r=n===te?M.ASTC8x5UnormSRGB:M.ASTC8x5Unorm;break;case wh:r=n===te?M.ASTC8x6UnormSRGB:M.ASTC8x6Unorm;break;case Mh:r=n===te?M.ASTC8x8UnormSRGB:M.ASTC8x8Unorm;break;case Ch:r=n===te?M.ASTC10x5UnormSRGB:M.ASTC10x5Unorm;break;case Eh:r=n===te?M.ASTC10x6UnormSRGB:M.ASTC10x6Unorm;break;case Ah:r=n===te?M.ASTC10x8UnormSRGB:M.ASTC10x8Unorm;break;case Rh:r=n===te?M.ASTC10x10UnormSRGB:M.ASTC10x10Unorm;break;case Nh:r=n===te?M.ASTC12x10UnormSRGB:M.ASTC12x10Unorm;break;case Ph:r=n===te?M.ASTC12x12UnormSRGB:M.ASTC12x12Unorm;break;case os:r=n===te?M.RGBA8UnormSRGB:M.RGBA8Unorm;break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case os:switch(s){case ao:r=M.RGBA8Snorm;break;case lo:r=M.RGBA16Sint;break;case $n:r=M.RGBA16Uint;break;case Xe:r=M.RGBA32Uint;break;case Et:r=M.RGBA32Sint;break;case Nt:r=n===te?M.RGBA8UnormSRGB:M.RGBA8Unorm;break;case rs:r=M.RGBA16Float;break;case Qt:r=M.RGBA32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",s)}break;case su:switch(s){case Bm:r=M.RGB9E5UFloat;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",s)}break;case iu:switch(s){case ao:r=M.R8Snorm;break;case lo:r=M.R16Sint;break;case $n:r=M.R16Uint;break;case Xe:r=M.R32Uint;break;case Et:r=M.R32Sint;break;case Nt:r=M.R8Unorm;break;case rs:r=M.R16Float;break;case Qt:r=M.R32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",s)}break;case cn:switch(s){case ao:r=M.RG8Snorm;break;case lo:r=M.RG16Sint;break;case $n:r=M.RG16Uint;break;case Xe:r=M.RG32Uint;break;case Et:r=M.RG32Sint;break;case Nt:r=M.RG8Unorm;break;case rs:r=M.RG16Float;break;case Qt:r=M.RG32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",s)}break;case Bs:switch(s){case $n:r=M.Depth16Unorm;break;case Xe:r=M.Depth24Plus;break;case Qt:r=M.Depth32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",s)}break;case ti:switch(s){case Fi:r=M.Depth24PlusStencil8;break;case Qt:e&&e.features.has($h.Depth32FloatStencil8)===!1&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),r=M.Depth32FloatStencil8;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",s)}break;case nu:switch(s){case Et:r=M.R32Sint;break;case Xe:r=M.R32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",s)}break;case ru:switch(s){case Et:r=M.RG32Sint;break;case Xe:r=M.RG32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",s)}break;case ou:switch(s){case Et:r=M.RGBA32Sint;break;case Xe:r=M.RGBA32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",s)}break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}return r}const RA=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,NA=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,Ef={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},PA=o=>{o=o.trim();const e=o.match(RA);if(e!==null&&e.length===4){const t=e[2],s=[];let i=null;for(;(i=NA.exec(t))!==null;)s.push({name:i[1],type:i[2]});const n=[];for(let h=0;h<s.length;h++){const{name:u,type:d}=s[h];let p=d;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=d.split("<")[0]),p=Ef[p]),n.push(new Gu(p,u))}const r=o.substring(e[0].length),a=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:Ef[a]||a,inputs:n,name:l,inputsCode:t,blockCode:r,outputType:a}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class FA extends $u{constructor(e){const{type:t,inputs:s,name:i,inputsCode:n,blockCode:r,outputType:a}=PA(e);super(t,s,i),this.inputsCode=n,this.blockCode=r,this.outputType=a}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class DA extends vy{parseFunction(e){return new FA(e)}}const kn=typeof self<"u"?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},OA={[Zs.READ_ONLY]:"read",[Zs.WRITE_ONLY]:"write",[Zs.READ_WRITE]:"read_write"},Af={[cr]:"repeat",[Ri]:"clamp",[hr]:"mirror"},ga={vertex:kn?kn.VERTEX:1,fragment:kn?kn.FRAGMENT:2,compute:kn?kn.COMPUTE:4},Rf={instance:!0,swizzleAssign:!1,storageBuffer:!0},BA={"^^":"tsl_xor"},IA={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},Nf={},ss={tsl_xor:new ct("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new ct("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new ct("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new ct("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new ct("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new ct("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new ct("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new ct("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new ct("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new ct("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new ct("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new ct("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new ct(`
|
|
323
|
+
`;this.mipmapSampler=e.createSampler({minFilter:ln.Linear}),this.flipYSampler=e.createSampler({minFilter:ln.Nearest}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:t}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:s}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:i})}getTransferPipeline(e){let t=this.transferPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Kn.TriangleStrip,stripIndexFormat:yr.Uint32},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return t===void 0&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Kn.TriangleStrip,stripIndexFormat:yr.Uint32},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:n,height:r}=t.size,a=this.getTransferPipeline(i),l=this.getFlipYPipeline(i),c=this.device.createTexture({size:{width:n,height:r,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s}),u=c.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:0}),d=this.device.createCommandEncoder({}),p=(f,m,x)=>{const g=f.getBindGroupLayout(0),_=this.device.createBindGroup({layout:g,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:m}]}),b=d.beginRenderPass({colorAttachments:[{view:x,loadOp:Ce.Clear,storeOp:Ct.Store,clearValue:[0,0,0,0]}]});b.setPipeline(f),b.setBindGroup(0,_),b.draw(4,1,0,0),b.end()};p(a,h,u),p(l,u,h),this.device.queue.submit([d.finish()]),c.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);i.useCount===void 0&&(i.useCount=0,i.layers=[]);const n=i.layers[s]||this._mipmapCreateBundles(e,t,s),r=this.device.createCommandEncoder({});this._mipmapRunBundles(r,n),this.device.queue.submit([r.finish()]),i.useCount!==0&&(i.layers[s]=n),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),n=i.getBindGroupLayout(0);let r=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s});const a=[];for(let l=1;l<t.mipLevelCount;l++){const c=this.device.createBindGroup({layout:n,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:r}]}),h=e.createView({baseMipLevel:l,mipLevelCount:1,dimension:ft.TwoD,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:Ce.Clear,storeOp:Ct.Store,clearValue:[0,0,0,0]}]},d=this.device.createRenderBundleEncoder({colorFormats:[t.format]});d.setPipeline(i),d.setBindGroup(0,c),d.draw(4,1,0,0),a.push({renderBundles:[d.finish()],passDescriptor:u}),r=h}return a}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const n=t[i],r=e.beginRenderPass(n.passDescriptor);r.executeBundles(n.renderBundles),r.end()}}}const ZA={[zm]:"never",[cu]:"less",[Gm]:"equal",[Vm]:"less-equal",[Hm]:"greater",[$m]:"greater-equal",[jm]:"always",[Wm]:"not-equal"},KA=[0,1,3,2,4,5];class QA{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new Is,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,s=t.device,i=t.get(e),n={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};n.magFilter===ln.Linear&&n.minFilter===ln.Linear&&n.mipmapFilter===ln.Linear&&(n.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&(n.compare=ZA[e.compareFunction]),i.sampler=s.createSampler(n)}createDefaultTexture(e){let t;const s=Yh(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:n,height:r,depth:a,levels:l}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const c=this._getDimension(e),h=e.internalFormat||t.format||Yh(e,s.device);i.format=h;const{samples:u,primarySamples:d,isMSAA:p}=s.utils.getTextureSampleData(e);let f=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(f|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&(f|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:n,height:r,depthOrArrayLayers:a},mipLevelCount:l,sampleCount:d,dimension:c,format:h,usage:f};if(e.isVideoTexture){const x=e.source.data,g=new VideoFrame(x);m.size.width=g.displayWidth,m.size.height=g.displayHeight,g.close(),i.externalTexture=x}else{if(h===void 0){console.warn("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(m.textureBindingViewDimension=ft.Cube),i.texture=s.device.createTexture(m)}if(p){const x=Object.assign({},m);x.label=x.label+"-msaa",x.sampleCount=u,i.msaaTexture=s.device.createTexture(x)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e){const t=this.backend,s=t.get(e);s.texture!==void 0&&s.texture.destroy(),s.msaaTexture!==void 0&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){const s=this.backend.get(e);delete s.sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let s=0;s<6;s++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,s);else{const s=e.image.depth||1;for(let i=0;i<s;i++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,i)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const s=this.backend,{width:i,height:n}=s.getDrawingBufferSize(),r=this.depthTexture,a=s.get(r).texture;let l,c;if(t?(l=ti,c=Fi):e&&(l=Bs,c=Xe),a!==void 0){if(r.image.width===i&&r.image.height===n&&r.format===l&&r.type===c)return a;this.destroyTexture(r)}return r.name="depthBuffer",r.format=l,r.type=c,r.image.width=i,r.image.height=n,this.createTexture(r,{width:i,height:n}),s.get(r).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:i}=s;if(!(e.isRenderTargetTexture||i===void 0)){if(e.isDataTexture)this._copyBufferToTexture(t.image,s.texture,i,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let n=0;n<t.image.depth;n++)this._copyBufferToTexture(t.image,s.texture,i,n,e.flipY,n);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,s.texture,i,e.flipY,e.premultiplyAlpha);else if(e.isVideoTexture){const n=e.source.data;s.externalTexture=n}else this._copyImageToTexture(t.image,s.texture,i,0,e.flipY,e.premultiplyAlpha);s.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,s,i,n,r){const a=this.backend.device,l=this.backend.get(e),c=l.texture,h=l.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let d=i*u;d=Math.ceil(d/256)*256;const p=a.createBuffer({size:i*n*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),f=a.createCommandEncoder();f.copyTextureToBuffer({texture:c,origin:{x:t,y:s,z:r}},{buffer:p,bytesPerRow:d},{width:i,height:n});const m=this._getTypedArrayType(h);a.queue.submit([f.finish()]),await p.mapAsync(GPUMapMode.READ);const x=p.getMappedRange();return new m(x)}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new St;s.minFilter=ut,s.magFilter=ut,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const s=new Cl;s.minFilter=ut,s.magFilter=ut,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(e===null){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,s,i,n){for(let r=0;r<6;r++){const a=e[r],l=i===!0?KA[r]:r;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,l,i):this._copyImageToTexture(a,t,s,l,i,n)}}_copyImageToTexture(e,t,s,i,n,r){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:n},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i},premultipliedAlpha:r},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new XA(this.backend.device)),e}_generateMipmaps(e,t,s=0){this._getPassUtils().generateMipmaps(e,t,s)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,n,r=0){const a=this.backend.device,l=e.data,c=this._getBytesPerTexel(s.format),h=e.width*c;a.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*c*r,bytesPerRow:h},{width:e.width,height:e.height,depthOrArrayLayers:1}),n===!0&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,n=this._getBlockData(s.format),r=s.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const l=e[a],c=l.width,h=l.height,u=r?s.size.depthOrArrayLayers:1,d=Math.ceil(c/n.width)*n.byteLength,p=d*Math.ceil(h/n.height);for(let f=0;f<u;f++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:f}},l.data,{offset:f*p,bytesPerRow:d,rowsPerImage:Math.ceil(h/n.height)},{width:Math.ceil(c/n.width)*n.width,height:Math.ceil(h/n.height)*n.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===M.BC1RGBAUnorm||e===M.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.BC2RGBAUnorm||e===M.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.BC3RGBAUnorm||e===M.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.BC4RUnorm||e===M.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===M.BC5RGUnorm||e===M.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===M.BC6HRGBUFloat||e===M.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===M.BC7RGBAUnorm||e===M.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.ETC2RGB8Unorm||e===M.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.ETC2RGB8A1Unorm||e===M.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===M.ETC2RGBA8Unorm||e===M.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===M.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===M.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===M.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===M.ASTC4x4Unorm||e===M.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===M.ASTC5x4Unorm||e===M.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===M.ASTC5x5Unorm||e===M.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===M.ASTC6x5Unorm||e===M.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===M.ASTC6x6Unorm||e===M.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===M.ASTC8x5Unorm||e===M.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===M.ASTC8x6Unorm||e===M.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===M.ASTC8x8Unorm||e===M.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===M.ASTC10x5Unorm||e===M.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===M.ASTC10x6Unorm||e===M.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===M.ASTC10x8Unorm||e===M.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===M.ASTC10x10Unorm||e===M.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===M.ASTC12x10Unorm||e===M.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===M.ASTC12x12Unorm||e===M.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=qc.ClampToEdge;return e===ur?t=qc.Repeat:e===dr&&(t=qc.MirrorRepeat),t}_convertFilterMode(e){let t=ln.Linear;return(e===ut||e===Um||e===_o)&&(t=ln.Nearest),t}_getBytesPerTexel(e){if(e===M.R8Unorm||e===M.R8Snorm||e===M.R8Uint||e===M.R8Sint)return 1;if(e===M.R16Uint||e===M.R16Sint||e===M.R16Float||e===M.RG8Unorm||e===M.RG8Snorm||e===M.RG8Uint||e===M.RG8Sint)return 2;if(e===M.R32Uint||e===M.R32Sint||e===M.R32Float||e===M.RG16Uint||e===M.RG16Sint||e===M.RG16Float||e===M.RGBA8Unorm||e===M.RGBA8UnormSRGB||e===M.RGBA8Snorm||e===M.RGBA8Uint||e===M.RGBA8Sint||e===M.BGRA8Unorm||e===M.BGRA8UnormSRGB||e===M.RGB9E5UFloat||e===M.RGB10A2Unorm||e===M.RG11B10UFloat||e===M.Depth32Float||e===M.Depth24Plus||e===M.Depth24PlusStencil8||e===M.Depth32FloatStencil8)return 4;if(e===M.RG32Uint||e===M.RG32Sint||e===M.RG32Float||e===M.RGBA16Uint||e===M.RGBA16Sint||e===M.RGBA16Float)return 8;if(e===M.RGBA32Uint||e===M.RGBA32Sint||e===M.RGBA32Float)return 16}_getTypedArrayType(e){if(e===M.R8Uint)return Uint8Array;if(e===M.R8Sint)return Int8Array;if(e===M.R8Unorm)return Uint8Array;if(e===M.R8Snorm)return Int8Array;if(e===M.RG8Uint)return Uint8Array;if(e===M.RG8Sint)return Int8Array;if(e===M.RG8Unorm)return Uint8Array;if(e===M.RG8Snorm)return Int8Array;if(e===M.RGBA8Uint)return Uint8Array;if(e===M.RGBA8Sint)return Int8Array;if(e===M.RGBA8Unorm)return Uint8Array;if(e===M.RGBA8Snorm)return Int8Array;if(e===M.R16Uint)return Uint16Array;if(e===M.R16Sint)return Int16Array;if(e===M.RG16Uint)return Uint16Array;if(e===M.RG16Sint)return Int16Array;if(e===M.RGBA16Uint)return Uint16Array;if(e===M.RGBA16Sint)return Int16Array;if(e===M.R16Float||e===M.RG16Float||e===M.RGBA16Float)return Uint16Array;if(e===M.R32Uint)return Uint32Array;if(e===M.R32Sint)return Int32Array;if(e===M.R32Float)return Float32Array;if(e===M.RG32Uint)return Uint32Array;if(e===M.RG32Sint)return Int32Array;if(e===M.RG32Float)return Float32Array;if(e===M.RGBA32Uint)return Uint32Array;if(e===M.RGBA32Sint)return Int32Array;if(e===M.RGBA32Float)return Float32Array;if(e===M.BGRA8Unorm||e===M.BGRA8UnormSRGB)return Uint8Array;if(e===M.RGB10A2Unorm||e===M.RGB9E5UFloat||e===M.RG11B10UFloat)return Uint32Array;if(e===M.Depth32Float)return Float32Array;if(e===M.Depth24Plus||e===M.Depth24PlusStencil8)return Uint32Array;if(e===M.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.isData3DTexture?t=Rf.ThreeD:t=Rf.TwoD,t}}function Yh(o,e=null){const t=o.format,s=o.type,i=o.colorSpace,n=Ue.getTransfer(i);let r;if(o.isCompressedTexture===!0||o.isCompressedArrayTexture===!0)switch(t){case Pa:r=n===te?M.BC1RGBAUnormSRGB:M.BC1RGBAUnorm;break;case Fa:r=n===te?M.BC2RGBAUnormSRGB:M.BC2RGBAUnorm;break;case Da:r=n===te?M.BC3RGBAUnormSRGB:M.BC3RGBAUnorm;break;case xh:r=n===te?M.ETC2RGB8UnormSRGB:M.ETC2RGB8Unorm;break;case _h:r=n===te?M.ETC2RGBA8UnormSRGB:M.ETC2RGBA8Unorm;break;case bh:r=n===te?M.ASTC4x4UnormSRGB:M.ASTC4x4Unorm;break;case Th:r=n===te?M.ASTC5x4UnormSRGB:M.ASTC5x4Unorm;break;case Sh:r=n===te?M.ASTC5x5UnormSRGB:M.ASTC5x5Unorm;break;case vh:r=n===te?M.ASTC6x5UnormSRGB:M.ASTC6x5Unorm;break;case wh:r=n===te?M.ASTC6x6UnormSRGB:M.ASTC6x6Unorm;break;case Mh:r=n===te?M.ASTC8x5UnormSRGB:M.ASTC8x5Unorm;break;case Ch:r=n===te?M.ASTC8x6UnormSRGB:M.ASTC8x6Unorm;break;case Eh:r=n===te?M.ASTC8x8UnormSRGB:M.ASTC8x8Unorm;break;case Ah:r=n===te?M.ASTC10x5UnormSRGB:M.ASTC10x5Unorm;break;case Rh:r=n===te?M.ASTC10x6UnormSRGB:M.ASTC10x6Unorm;break;case Nh:r=n===te?M.ASTC10x8UnormSRGB:M.ASTC10x8Unorm;break;case Ph:r=n===te?M.ASTC10x10UnormSRGB:M.ASTC10x10Unorm;break;case Fh:r=n===te?M.ASTC12x10UnormSRGB:M.ASTC12x10Unorm;break;case Dh:r=n===te?M.ASTC12x12UnormSRGB:M.ASTC12x12Unorm;break;case os:r=n===te?M.RGBA8UnormSRGB:M.RGBA8Unorm;break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case os:switch(s){case co:r=M.RGBA8Snorm;break;case ho:r=M.RGBA16Sint;break;case jn:r=M.RGBA16Uint;break;case Xe:r=M.RGBA32Uint;break;case Et:r=M.RGBA32Sint;break;case Nt:r=n===te?M.RGBA8UnormSRGB:M.RGBA8Unorm;break;case rs:r=M.RGBA16Float;break;case Kt:r=M.RGBA32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",s)}break;case nu:switch(s){case km:r=M.RGB9E5UFloat;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",s)}break;case ru:switch(s){case co:r=M.R8Snorm;break;case ho:r=M.R16Sint;break;case jn:r=M.R16Uint;break;case Xe:r=M.R32Uint;break;case Et:r=M.R32Sint;break;case Nt:r=M.R8Unorm;break;case rs:r=M.R16Float;break;case Kt:r=M.R32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",s)}break;case cn:switch(s){case co:r=M.RG8Snorm;break;case ho:r=M.RG16Sint;break;case jn:r=M.RG16Uint;break;case Xe:r=M.RG32Uint;break;case Et:r=M.RG32Sint;break;case Nt:r=M.RG8Unorm;break;case rs:r=M.RG16Float;break;case Kt:r=M.RG32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",s)}break;case Bs:switch(s){case jn:r=M.Depth16Unorm;break;case Xe:r=M.Depth24Plus;break;case Kt:r=M.Depth32Float;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",s)}break;case ti:switch(s){case Fi:r=M.Depth24PlusStencil8;break;case Kt:e&&e.features.has(qh.Depth32FloatStencil8)===!1&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),r=M.Depth32FloatStencil8;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",s)}break;case ou:switch(s){case Et:r=M.R32Sint;break;case Xe:r=M.R32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",s)}break;case au:switch(s){case Et:r=M.RG32Sint;break;case Xe:r=M.RG32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",s)}break;case lu:switch(s){case Et:r=M.RGBA32Sint;break;case Xe:r=M.RGBA32Uint;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",s)}break;default:console.error("WebGPURenderer: Unsupported texture format.",t)}return r}const JA=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,eR=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,Nf={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},tR=o=>{o=o.trim();const e=o.match(JA);if(e!==null&&e.length===4){const t=e[2],s=[];let i=null;for(;(i=eR.exec(t))!==null;)s.push({name:i[1],type:i[2]});const n=[];for(let h=0;h<s.length;h++){const{name:u,type:d}=s[h];let p=d;p.startsWith("ptr")?p="pointer":(p.startsWith("texture")&&(p=d.split("<")[0]),p=Nf[p]),n.push(new Wu(p,u))}const r=o.substring(e[0].length),a=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:Nf[a]||a,inputs:n,name:l,inputsCode:t,blockCode:r,outputType:a}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class sR extends qu{constructor(e){const{type:t,inputs:s,name:i,inputsCode:n,blockCode:r,outputType:a}=tR(e);super(t,s,i),this.inputsCode=n,this.blockCode=r,this.outputType=a}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class iR extends Ey{parseFunction(e){return new sR(e)}}const zn=typeof self<"u"?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},nR={[Zs.READ_ONLY]:"read",[Zs.WRITE_ONLY]:"write",[Zs.READ_WRITE]:"read_write"},Pf={[ur]:"repeat",[Ri]:"clamp",[dr]:"mirror"},ya={vertex:zn?zn.VERTEX:1,fragment:zn?zn.FRAGMENT:2,compute:zn?zn.COMPUTE:4},Ff={instance:!0,swizzleAssign:!1,storageBuffer:!0},rR={"^^":"tsl_xor"},oR={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},Df={},ss={tsl_xor:new ct("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new ct("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new ct("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new ct("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new ct("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new ct("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new ct("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new ct("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new ct("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new ct("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new ct("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new ct("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new ct(`
|
|
324
324
|
fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
|
|
325
325
|
|
|
326
326
|
let res = vec2f( iRes );
|
|
@@ -342,17 +342,17 @@ fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, l
|
|
|
342
342
|
return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
|
|
343
343
|
|
|
344
344
|
}
|
|
345
|
-
`)},
|
|
346
|
-
`);class
|
|
345
|
+
`)},no={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>"};typeof navigator<"u"&&/Windows/g.test(navigator.userAgent)&&(ss.pow_float=new ct("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),ss.pow_vec2=new ct("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[ss.pow_float]),ss.pow_vec3=new ct("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[ss.pow_float]),ss.pow_vec4=new ct("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[ss.pow_float]),no.pow_float="tsl_pow_float",no.pow_vec2="tsl_pow_vec2",no.pow_vec3="tsl_pow_vec3",no.pow_vec4="tsl_pow_vec4");let Gy="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(Gy+=`diagnostic( off, derivative_uniformity );
|
|
346
|
+
`);class aR extends Cy{constructor(e,t){super(e,t,new iR),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==ri}_generateTextureSample(e,t,s,i,n=this.shaderStage){return n==="fragment"?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this._generateTextureSampleLevel(e,t,s,"0",i)}_generateVideoSample(e,t,s=this.shaderStage){if(s==="fragment")return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,n){return this.isUnfilterable(e)===!1?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,n,i)}generateWrapFunction(e){const t=`tsl_coord_${Pf[e.wrapS]}S_${Pf[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let s=Df[t];if(s===void 0){const i=[],n=e.isData3DTexture?"vec3f":"vec2f";let r=`fn ${t}( coord : ${n} ) -> ${n} {
|
|
347
347
|
|
|
348
348
|
return ${n}(
|
|
349
|
-
`;const a=(l,c)=>{l===
|
|
349
|
+
`;const a=(l,c)=>{l===ur?(i.push(ss.repeatWrapping_float),r+=` tsl_repeatWrapping_float( coord.${c} )`):l===Ri?(i.push(ss.clampWrapping_float),r+=` tsl_clampWrapping_float( coord.${c} )`):l===dr?(i.push(ss.mirrorWrapping_float),r+=` tsl_mirrorWrapping_float( coord.${c} )`):(r+=` coord.${c}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${l}" for vertex shader.`))};a(e.wrapS,"x"),r+=`,
|
|
350
350
|
`,a(e.wrapT,"y"),e.isData3DTexture&&(r+=`,
|
|
351
351
|
`,a(e.wrapR,"z")),r+=`
|
|
352
352
|
);
|
|
353
353
|
|
|
354
354
|
}
|
|
355
|
-
`,
|
|
355
|
+
`,Df[t]=s=new ct(r,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);i.dimensionsSnippet===void 0&&(i.dimensionsSnippet={});let n=i.dimensionsSnippet[s];if(i.dimensionsSnippet[s]===void 0){let r,a;const{primarySamples:l}=this.renderer.backend.utils.getTextureSampleData(e),c=l>1;e.isData3DTexture?a="vec3<u32>":a="vec2<u32>",c||e.isVideoTexture||e.isStorageTexture?r=t:r=`${t}${s?`, u32( ${s} )`:""}`,n=new Ia(new Ua(`textureDimensions( ${r} )`,a)),i.dimensionsSnippet[s]=n,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Ia(new Ua(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Ia(new Ua("6u","u32")))}return n.build(this)}generateFilteredTexture(e,t,s,i="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),r=this.generateTextureDimension(e,t,i);return`tsl_biquadraticTexture( ${t}, ${n}( ${s} ), ${r}, u32( ${i} ) )`}generateTextureLod(e,t,s,i,n="0u"){const r=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,n),l=e.isData3DTexture?"vec3":"vec2",c=`${l}<u32>( ${r}( ${s} ) * ${l}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,c,i,n)}generateTextureLoad(e,t,s,i,n="0u"){let r;return e.isVideoTexture===!0?r=`textureLoad( ${t}, ${s} )`:i?r=`textureLoad( ${t}, ${s}, ${i}, u32( ${n} ) )`:(r=`textureLoad( ${t}, ${s}, u32( ${n} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(r+=".x")),r}generateTextureStore(e,t,s,i,n){let r;return i?r=`textureStore( ${t}, ${s}, ${i}, ${n} )`:r=`textureStore( ${t}, ${s}, ${n} )`,r}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.isDataTexture===!0&&e.type===Kt||this.isSampleCompare(e)===!1&&e.minFilter===ut&&e.magFilter===ut||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,n=this.shaderStage){let r=null;return e.isVideoTexture===!0?r=this._generateVideoSample(t,s,n):this.isUnfilterable(e)?r=this.generateTextureLod(e,t,s,i,"0",n):r=this._generateTextureSample(e,t,s,i,n),r}generateTextureGrad(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${r} shader.`)}generateTextureCompare(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${n}, ${i} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${r} shader.`)}generateTextureLevel(e,t,s,i,n,r=this.shaderStage){let a=null;return e.isVideoTexture===!0?a=this._generateVideoSample(t,s,r):a=this._generateTextureSampleLevel(e,t,s,i,n),a}generateTextureBias(e,t,s,i,n,r=this.shaderStage){if(r==="fragment")return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${r} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){const s=e.name,i=e.type;return i==="texture"||i==="cubeTexture"||i==="storageTexture"||i==="texture3D"?s:i==="buffer"||i==="storageBuffer"||i==="indirectStorageBuffer"?this.isCustomStruct(e)?s:s+".value":e.groupNode.name+"."+s}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=rR[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?Zs.READ_ONLY:e.access}getStorageAccess(e,t){return nR[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const n=super.getUniformFromNode(e,t,s,i),r=this.getDataFromNode(e,s,this.globalCache);if(r.uniformGPU===void 0){let a;const l=e.groupNode,c=l.name,h=this.getBindGroupArray(c,s);if(t==="texture"||t==="cubeTexture"||t==="storageTexture"||t==="texture3D"){let u=null;const d=this.getNodeAccess(e,s);if(t==="texture"||t==="storageTexture"?u=new Pl(n.name,n.node,l,d):t==="cubeTexture"?u=new Ly(n.name,n.node,l,d):t==="texture3D"&&(u=new Uy(n.name,n.node,l,d)),u.store=e.isStorageTextureNode===!0,u.setVisibility(ya[s]),this.isUnfilterable(e.value)===!1&&u.store===!1){const p=new $A(`${n.name}_sampler`,n.node,l);p.setVisibility(ya[s]),h.push(p,u),a=[p,u]}else h.push(u),a=[u]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const u=t==="buffer"?By:YA,d=new u(e,l);d.setVisibility(ya[s]),h.push(d),a=d,n.name=i||"NodeBuffer_"+n.id}else{const u=this.uniformGroups[s]||(this.uniformGroups[s]={});let d=u[c];d===void 0&&(d=new Iy(c,l),d.setVisibility(ya[s]),u[c]=d,h.push(d)),a=this.getNodeUniform(n,t),d.addUniform(a)}r.uniformGPU=a}return n}getBuiltin(e,t,s,i=this.shaderStage){const n=this.builtins[i]||(this.builtins[i]=new Map);return n.has(e)===!1&&n.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const r of t.inputs)i.push(r.name+" : "+this.getType(r.type));let n=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {
|
|
356
356
|
${s.vars}
|
|
357
357
|
${s.code}
|
|
358
358
|
`;return s.result&&(n+=` return ${s.result};
|
|
@@ -373,7 +373,7 @@ ${s.code}
|
|
|
373
373
|
${t.join(`
|
|
374
374
|
`)}
|
|
375
375
|
`}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const n=this.varyings,r=this.vars[e];for(let a=0;a<n.length;a++){const l=n[a];if(l.needsInterpolation){let c=`@location( ${a} )`;if(l.interpolationType){const h=l.interpolationSampling!==null?`, ${l.interpolationSampling} )`:" )";c+=` @interpolate( ${l.interpolationType}${h}`}else/^(int|uint|ivec|uvec)/.test(l.type)&&(c+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${c} ${l.name} : ${this.getType(l.type)}`)}else e==="vertex"&&r.includes(l)===!1&&r.push(l)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(`,
|
|
376
|
-
`);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&s.structTypeNode!==null,n=s.value&&s.value.array&&typeof s.value.itemSize=="number"&&s.value.array.length>s.value.itemSize;return i&&!n}getUniforms(e){const t=this.uniforms[e],s=[],i=[],n=[],r={};for(const l of t){const c=l.groupNode.name,h=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="storageTexture"||l.type==="texture3D"){const u=l.node.value;this.isUnfilterable(u)===!1&&l.node.isStorageTextureNode!==!0&&(this.isSampleCompare(u)?s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler_comparison;`):s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler;`));let d,p="";const{primarySamples:f}=this.renderer.backend.utils.getTextureSampleData(u);if(f>1&&(p="_multisampled"),u.isCubeTexture===!0)d="texture_cube<f32>";else if(u.isDepthTexture===!0)this.renderer.backend.compatibilityMode&&u.compareFunction===null?d=`texture${p}_2d<f32>`:d=`texture_depth${p}_2d${u.isArrayTexture===!0?"_array":""}`;else if(u.isArrayTexture===!0||u.isDataArrayTexture===!0||u.isCompressedArrayTexture===!0)d="texture_2d_array<f32>";else if(u.isVideoTexture===!0)d="texture_external";else if(u.isData3DTexture===!0)d="texture_3d<f32>";else if(l.node.isStorageTextureNode===!0){const m=
|
|
376
|
+
`);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&s.structTypeNode!==null,n=s.value&&s.value.array&&typeof s.value.itemSize=="number"&&s.value.array.length>s.value.itemSize;return i&&!n}getUniforms(e){const t=this.uniforms[e],s=[],i=[],n=[],r={};for(const l of t){const c=l.groupNode.name,h=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="storageTexture"||l.type==="texture3D"){const u=l.node.value;this.isUnfilterable(u)===!1&&l.node.isStorageTextureNode!==!0&&(this.isSampleCompare(u)?s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler_comparison;`):s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler;`));let d,p="";const{primarySamples:f}=this.renderer.backend.utils.getTextureSampleData(u);if(f>1&&(p="_multisampled"),u.isCubeTexture===!0)d="texture_cube<f32>";else if(u.isDepthTexture===!0)this.renderer.backend.compatibilityMode&&u.compareFunction===null?d=`texture${p}_2d<f32>`:d=`texture_depth${p}_2d${u.isArrayTexture===!0?"_array":""}`;else if(u.isArrayTexture===!0||u.isDataArrayTexture===!0||u.isCompressedArrayTexture===!0)d="texture_2d_array<f32>";else if(u.isVideoTexture===!0)d="texture_external";else if(u.isData3DTexture===!0)d="texture_3d<f32>";else if(l.node.isStorageTextureNode===!0){const m=Yh(u),x=this.getStorageAccess(l.node,e);d=`texture_storage_2d<${m}, ${x}>`}else{const m=this.getComponentTypeFromTexture(u).charAt(0);d=`texture${p}_2d<${m}32>`}s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name} : ${d};`)}else if(l.type==="buffer"||l.type==="storageBuffer"||l.type==="indirectStorageBuffer"){const u=l.node,d=this.getType(u.getNodeType(this)),p=u.bufferCount,f=p>0&&l.type==="buffer"?", "+p:"",m=u.isStorageBufferNode?`storage, ${this.getStorageAccess(u,e)}`:"uniform";if(this.isCustomStruct(l))i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var<${m}> ${l.name} : ${d};`);else{const g=` value : array< ${u.isAtomic?`atomic<${d}>`:`${d}`}${f} >`;i.push(this._getWGSLStructBinding(l.name,g,m,h.binding++,h.group))}}else{const u=this.getType(this.getVectorType(l.type)),d=l.groupNode.name;(r[d]||(r[d]={index:h.binding++,id:h.group,snippets:[]})).snippets.push(` ${l.name} : ${u}`)}}for(const l in r){const c=r[l];n.push(this._getWGSLStructBinding(l,c.snippets.join(`,
|
|
377
377
|
`),"uniform",c.index,c.id))}let a=s.join(`
|
|
378
378
|
`);return a+=i.join(`
|
|
379
379
|
`),a+=n.join(`
|
|
@@ -388,7 +388,7 @@ ${t.join(`
|
|
|
388
388
|
`+p),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",d),s.structs+=`
|
|
389
389
|
var<private> output : OutputStruct;`,i+=`output.color = ${h.result};
|
|
390
390
|
|
|
391
|
-
return output;`}}}s.flow=i}this.shaderStage=null,this.material!==null?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return t!==null&&(s=this._getWGSLMethod(e+"_"+t)),s===void 0&&(s=this._getWGSLMethod(e)),s||e}getType(e){return
|
|
391
|
+
return output;`}}}s.flow=i}this.shaderStage=null,this.material!==null?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return t!==null&&(s=this._getWGSLMethod(e+"_"+t)),s===void 0&&(s=this._getWGSLMethod(e)),s||e}getType(e){return oR[e]||e}isAvailable(e){let t=Ff[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),Ff[e]=t),t}_getWGSLMethod(e){return ss[e]!==void 0&&this._include(e),no[e]}_include(e){const t=ss[e];return t.build(this),this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
|
|
392
392
|
// directives
|
|
393
393
|
${e.directives}
|
|
394
394
|
|
|
@@ -419,7 +419,7 @@ fn main( ${e.attributes} ) -> VaryingsStruct {
|
|
|
419
419
|
}
|
|
420
420
|
`}_getWGSLFragmentCode(e){return`${this.getSignature()}
|
|
421
421
|
// global
|
|
422
|
-
${
|
|
422
|
+
${Gy}
|
|
423
423
|
|
|
424
424
|
// structs
|
|
425
425
|
${e.structs}
|
|
@@ -477,12 +477,12 @@ struct ${e} {
|
|
|
477
477
|
${t}
|
|
478
478
|
};`}_getWGSLStructBinding(e,t,s,i=0,n=0){const r=e+"Struct";return`${this._getWGSLStruct(r,t)}
|
|
479
479
|
@binding( ${i} ) @group( ${n} )
|
|
480
|
-
var<${s}> ${e} : ${r};`}}class UA{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=M.Depth24PlusStencil8:e.depth&&(t=M.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const n=this.backend.renderer,r=n.getRenderTarget();t=r?r.samples:n.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return Zn.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return Zn.LineList;if(e.isLine)return Zn.LineStrip;if(e.isMesh)return Zn.TriangleList}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),t===2&&(t=4)),t}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(e===void 0)return navigator.gpu.getPreferredCanvasFormat();if(e===Nt)return M.BGRA8Unorm;if(e===rs)return M.RGBA16Float;throw new Error("Unsupported outputType")}}const kA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),zA=new Map([[Zm,["float16"]]]),VA=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class GA{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,n=i.get(s);let r=n.buffer;if(r===void 0){const a=i.device;let l=s.array;if(e.normalized===!1){if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let u=0;u<l.length;u++)l[u]===65535&&(l[u]=4294967295)}if(s.array=l,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&s.itemSize===3){l=new l.constructor(s.count*4);for(let u=0;u<s.count;u++)l.set(s.array.subarray(u*3,u*3+3),u*4);s.itemSize=4,s.array=l,n._force3to4BytesAlignment=!0}const c=l.byteLength,h=c+(4-c%4)%4;r=a.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new l.constructor(r.getMappedRange()).set(l),r.unmap(),n.buffer=r}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,n=s.get(t),r=s.get(t).buffer;let a=t.array;if(n._force3to4BytesAlignment===!0){a=new a.constructor(t.count*4);for(let h=0;h<t.count;h++)a.set(t.array.subarray(h*3,h*3+3),h*4);t.array=a}const l=this._isTypedArray(a),c=t.updateRanges;if(c.length===0)i.queue.writeBuffer(r,0,a,0);else{const h=l?1:a.BYTES_PER_ELEMENT;for(let u=0,d=c.length;u<d;u++){const p=c[u];let f,m;if(n._force3to4BytesAlignment===!0){const g=Math.floor(p.start/3),_=Math.ceil(p.count/3);f=g*4*h,m=_*4*h}else f=p.start*h,m=p.count*h;const y=f*(l?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(r,y,a,f,m)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let i=0;i<t.length;i++){const n=t[i],r=n.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(n);let l=s.get(a);if(l===void 0){let u,d;n.isInterleavedBufferAttribute===!0?(u=n.data.stride*r,d=n.data.isInstancedInterleavedBuffer?ma.Instance:ma.Vertex):(u=n.itemSize*r,d=n.isInstancedBufferAttribute?ma.Instance:ma.Vertex),n.normalized===!1&&(n.array.constructor===Int16Array||n.array.constructor===Uint16Array)&&(u=4),l={arrayStride:u,attributes:[],stepMode:d},s.set(a,l)}const c=this._getVertexFormat(n),h=n.isInterleavedBufferAttribute===!0?n.offset*r:0;l.attributes.push({shaderLocation:i,offset:h,format:c})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,n=t.get(this._getBufferAttribute(e)).buffer,r=n.size,a=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),l=s.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(n,0,a,0,r);const c=l.finish();s.queue.submit([c]),await a.mapAsync(GPUMapMode.READ);const h=a.getMappedRange(),u=new e.array.constructor(h.slice(0));return a.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,n=e.constructor;let r;if(t===1)r=VA.get(i);else{const l=(zA.get(n)||kA.get(i))[s?1:0];if(l){const c=i.BYTES_PER_ELEMENT*t,u=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(u%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");r=`${l}x${u}`}}return r||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),r}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class HA{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,s=t.device,i=[];let n=0;for(const r of e.bindings){const a={binding:n++,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const l={};r.isStorageBuffer&&(r.visibility&4&&(r.access===Zs.READ_WRITE||r.access===Zs.WRITE_ONLY)?l.type=$c.Storage:l.type=$c.ReadOnlyStorage),a.buffer=l}else if(r.isSampler){const l={};r.texture.isDepthTexture&&(r.texture.compareFunction!==null?l.type=Mf.Comparison:t.compatibilityMode&&(l.type=Mf.NonFiltering)),a.sampler=l}else if(r.isSampledTexture&&r.texture.isVideoTexture)a.externalTexture={};else if(r.isSampledTexture&&r.store){const l={};l.format=this.backend.get(r.texture).texture.format;const c=r.access;c===Zs.READ_WRITE?l.access=jc.ReadWrite:c===Zs.WRITE_ONLY?l.access=jc.WriteOnly:l.access=jc.ReadOnly,a.storageTexture=l}else if(r.isSampledTexture){const l={},{primarySamples:c}=t.utils.getTextureSampleData(r.texture);if(c>1&&(l.multisampled=!0,r.texture.isDepthTexture||(l.sampleType=Yi.UnfilterableFloat)),r.texture.isDepthTexture)t.compatibilityMode&&r.texture.compareFunction===null?l.sampleType=Yi.UnfilterableFloat:l.sampleType=Yi.Depth;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const h=r.texture.type;h===Et?l.sampleType=Yi.SInt:h===Xe?l.sampleType=Yi.UInt:h===Qt&&(this.backend.hasFeature("float32-filterable")?l.sampleType=Yi.Float:l.sampleType=Yi.UnfilterableFloat)}r.isSampledCubeTexture?l.viewDimension=ft.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?l.viewDimension=ft.TwoDArray:r.isSampledTexture3D&&(l.viewDimension=ft.ThreeD),a.texture=l}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);i.push(a)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,s,i=0){const{backend:n,bindGroupLayoutCache:r}=this,a=n.get(e);let l=r.get(e.bindingsReference);l===void 0&&(l=this.createBindingsLayout(e),r.set(e.bindingsReference,l));let c;s>0&&(a.groups===void 0&&(a.groups=[],a.versions=[]),a.versions[s]===i&&(c=a.groups[s])),c===void 0&&(c=this.createBindGroup(e,l),s>0&&(a.groups[s]=c,a.versions[s]=i)),a.group=c,a.layout=l}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,n=t.get(e).buffer;s.queue.writeBuffer(n,0,i,0)}createBindGroupIndex(e,t){const i=this.backend.device,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],a=i.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:n});i.queue.writeBuffer(a,0,e,0);const l=[{binding:0,resource:{buffer:a}}];return i.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:l})}createBindGroup(e,t){const s=this.backend,i=s.device;let n=0;const r=[];for(const a of e.bindings){if(a.isUniformBuffer){const l=s.get(a);if(l.buffer===void 0){const c=a.byteLength,h=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,u=i.createBuffer({label:"bindingBuffer_"+a.name,size:c,usage:h});l.buffer=u}r.push({binding:n,resource:{buffer:l.buffer}})}else if(a.isStorageBuffer){const l=s.get(a);if(l.buffer===void 0){const c=a.attribute;l.buffer=s.get(c).buffer}r.push({binding:n,resource:{buffer:l.buffer}})}else if(a.isSampler){const l=s.get(a.texture);r.push({binding:n,resource:l.sampler})}else if(a.isSampledTexture){const l=s.get(a.texture);let c;if(l.externalTexture!==void 0)c=i.importExternalTexture({source:l.externalTexture});else{const h=a.store?1:l.texture.mipLevelCount,u=`view-${l.texture.width}-${l.texture.height}-${h}`;if(c=l[u],c===void 0){const d=_A.All;let p;a.isSampledCubeTexture?p=ft.Cube:a.isSampledTexture3D?p=ft.ThreeD:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?p=ft.TwoDArray:p=ft.TwoD,c=l[u]=l.texture.createView({aspect:d,dimension:p,mipLevelCount:h})}}r.push({binding:n,resource:c})}n++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:r})}}class WA{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:n,pipeline:r}=e,{vertexProgram:a,fragmentProgram:l}=r,c=this.backend,h=c.device,u=c.utils,d=c.get(r),p=[];for(const j of e.getBindings()){const X=c.get(j);p.push(X.layout)}const f=c.attributeUtils.createShaderVertexBuffers(e);let m;i.blending!==lr&&(i.blending!==Js||i.transparent!==!1)&&(m=this._getBlending(i));let y={};i.stencilWrite===!0&&(y={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(e.context.textures!==null){const j=e.context.textures;for(let X=0;X<j.length;X++){const Z=u.getTextureFormatGPU(j[X]);_.push({format:Z,blend:m,writeMask:g})}}else{const j=u.getCurrentColorFormat(e.context);_.push({format:j,blend:m,writeMask:g})}const b=c.get(a).module,T=c.get(l).module,S=this._getPrimitiveState(s,n,i),C=this._getDepthCompare(i),w=u.getCurrentDepthStencilFormat(e.context),R=this._getSampleCount(e.context),P={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:f}),fragment:Object.assign({},T,{targets:_}),primitive:S,multisample:{count:R,alphaToCoverageEnabled:i.alphaToCoverage&&R>1},layout:h.createPipelineLayout({bindGroupLayouts:p})},z={},$=e.context.depth,q=e.context.stencil;if(($===!0||q===!0)&&($===!0&&(z.format=w,z.depthWriteEnabled=i.depthWrite,z.depthCompare=C),q===!0&&(z.stencilFront=y,z.stencilBack={},z.stencilReadMask=i.stencilFuncMask,z.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&(z.depthBias=i.polygonOffsetUnits,z.depthBiasSlopeScale=i.polygonOffsetFactor,z.depthBiasClamp=0),P.depthStencil=z),t===null)d.pipeline=h.createRenderPipeline(P);else{const j=new Promise(X=>{h.createRenderPipelineAsync(P).then(Z=>{d.pipeline=Z,X()})});t.push(j)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:n}=s,r=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormat(e),l=this._getSampleCount(e),c={label:t,colorFormats:[a],depthStencilFormat:r,sampleCount:l};return n.createRenderBundleEncoder(c)}createComputePipeline(e,t){const s=this.backend,i=s.device,n=s.get(e.computeProgram).module,r=s.get(e),a=[];for(const l of t){const c=s.get(l);a.push(c.layout)}r.pipeline=i.createComputePipeline({compute:n,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,s;const i=e.blending,n=e.blendSrc,r=e.blendDst,a=e.blendEquation;if(i===oo){const l=e.blendSrcAlpha!==null?e.blendSrcAlpha:n,c=e.blendDstAlpha!==null?e.blendDstAlpha:r,h=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(r),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(h)}}else{const l=e.premultipliedAlpha,c=(h,u,d,p)=>{t={srcFactor:h,dstFactor:u,operation:qi.Add},s={srcFactor:d,dstFactor:p,operation:qi.Add}};if(l)switch(i){case Js:c(ie.One,ie.OneMinusSrcAlpha,ie.One,ie.OneMinusSrcAlpha);break;case Ha:c(ie.One,ie.One,ie.One,ie.One);break;case Wa:c(ie.Zero,ie.OneMinusSrc,ie.Zero,ie.One);break;case $a:c(ie.Zero,ie.Src,ie.Zero,ie.SrcAlpha);break}else switch(i){case Js:c(ie.SrcAlpha,ie.OneMinusSrcAlpha,ie.One,ie.OneMinusSrcAlpha);break;case Ha:c(ie.SrcAlpha,ie.One,ie.SrcAlpha,ie.One);break;case Wa:c(ie.Zero,ie.OneMinusSrc,ie.Zero,ie.One);break;case $a:c(ie.Zero,ie.Src,ie.Zero,ie.Src);break}}if(t!==void 0&&s!==void 0)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case vi:t=ie.Zero;break;case _m:t=ie.One;break;case bm:t=ie.Src;break;case Tm:t=ie.OneMinusSrc;break;case ja:t=ie.SrcAlpha;break;case qa:t=ie.OneMinusSrcAlpha;break;case wm:t=ie.Dst;break;case Mm:t=ie.OneMinusDst;break;case Sm:t=ie.DstAlpha;break;case vm:t=ie.OneMinusDstAlpha;break;case Cm:t=ie.SrcAlphaSaturated;break;case q_:t=ie.Constant;break;case Y_:t=ie.OneMinusConstant;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case E_:t=gt.Never;break;case Fh:t=gt.Always;break;case A_:t=gt.Less;break;case N_:t=gt.LessEqual;break;case R_:t=gt.Equal;break;case D_:t=gt.GreaterEqual;break;case P_:t=gt.Greater;break;case F_:t=gt.NotEqual;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case en:t=_i.Keep;break;case b_:t=_i.Zero;break;case T_:t=_i.Replace;break;case C_:t=_i.Invert;break;case S_:t=_i.IncrementClamp;break;case v_:t=_i.DecrementClamp;break;case w_:t=_i.IncrementWrap;break;case M_:t=_i.DecrementWrap;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case bs:t=qi.Add;break;case ym:t=qi.Subtract;break;case xm:t=qi.ReverseSubtract;break;case n_:t=qi.Min;break;case r_:t=qi.Max;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},n=this.backend.utils;switch(i.topology=n.getPrimitiveTopology(e,s),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?mr.Uint16:mr.Uint32),s.side){case Ks:i.frontFace=Gc.CCW,i.cullMode=Hc.Back;break;case Vt:i.frontFace=Gc.CCW,i.cullMode=Hc.Front;break;case Qn:i.frontFace=Gc.CCW,i.cullMode=Hc.None;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side);break}return i}_getColorWriteMask(e){return e.colorWrite===!0?wf.All:wf.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=gt.Always;else{const s=e.depthFunc;switch(s){case Em:t=gt.Never;break;case Am:t=gt.Always;break;case Rm:t=gt.Less;break;case Ya:t=gt.LessEqual;break;case Nm:t=gt.Equal;break;case Pm:t=gt.GreaterEqual;break;case Fm:t=gt.Greater;break;case Dm:t=gt.NotEqual;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class $A extends Iy{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return oi(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const n=i.finish();if(this.device.queue.submit([n]),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const r=new BigUint64Array(this.resultBuffer.getMappedRange(0,s));let a=0;for(const[,l]of e){const c=r[l],h=r[l+1],u=Number(h-c)/1e6;a+=u}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class jA extends By{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.compatibilityMode=e.compatibilityMode===void 0?!1:e.compatibilityMode,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new UA(this),this.attributeUtils=new GA(this),this.bindingUtils=new HA(this),this.pipelineUtils=new WA(this),this.textureUtils=new AA(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(t.device===void 0){const r={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},a=typeof navigator<"u"?await navigator.gpu.requestAdapter(r):null;if(a===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const l=Object.values($h),c=[];for(const u of l)a.features.has(u)&&c.push(u);const h={requiredFeatures:c,requiredLimits:t.requiredLimits};s=await a.requestDevice(h)}else s=t.device;s.lost.then(r=>{const a={api:"WebGPU",message:r.message||"Unknown reason",reason:r.reason||null,originalEvent:r};e.onDeviceLost(a)});const i=t.context!==void 0?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const n=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature($h.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n}),this.updateSize()}get coordinateSystem(){return Oi}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(e===null){const s=this.renderer;e={colorAttachments:[{view:null}]},(this.renderer.depth===!0||this.renderer.stencil===!0)&&(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(s.depth,s.stencil).createView()});const i=e.colorAttachments[0];this.renderer.samples>0?i.view=this.colorBuffer.createView():i.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let n=i.descriptors;if(n===void 0||i.width!==s.width||i.height!==s.height||i.dimensions!==s.dimensions||i.activeMipmapLevel!==e.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples){n={},i.descriptors=n;const c=()=>{s.removeEventListener("dispose",c),this.delete(s)};s.hasEventListener("dispose",c)===!1&&s.addEventListener("dispose",c)}const r=e.getCacheKey();let a=n[r];if(a===void 0){const c=e.textures,h=[];let u;const d=this._isRenderCameraDepthArray(e);for(let p=0;p<c.length;p++){const f=this.get(c[p]),m={label:`colorAttachment_${p}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:ft.TwoD};if(s.isRenderTarget3D)u=e.activeCubeFace,m.baseArrayLayer=0,m.dimension=ft.ThreeD,m.depthOrArrayLayers=c[p].image.depth;else if(s.isRenderTarget&&c[p].image.depth>1)if(d===!0){const y=e.camera.cameras;for(let g=0;g<y.length;g++){const _={...m,baseArrayLayer:g,arrayLayerCount:1,dimension:ft.TwoD},b=f.texture.createView(_);h.push({view:b,resolveTarget:void 0,depthSlice:void 0})}}else m.dimension=ft.TwoDArray,m.depthOrArrayLayers=c[p].image.depth;if(d!==!0){const y=f.texture.createView(m);let g,_;f.msaaTexture!==void 0?(g=f.msaaTexture.createView(),_=y):(g=y,_=void 0),h.push({view:g,resolveTarget:_,depthSlice:u})}}if(a={textureViews:h},e.depth){const p=this.get(e.depthTexture),f={};e.depthTexture.isArrayTexture&&(f.dimension=ft.TwoD,f.arrayLayerCount=1,f.baseArrayLayer=e.activeCubeFace),a.depthStencilView=p.texture.createView(f)}n[r]=a,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace,i.dimensions=s.dimensions}const l={colorAttachments:[]};for(let c=0;c<a.textureViews.length;c++){const h=a.textureViews[c];let u={r:0,g:0,b:0,a:1};c===0&&t.clearValue&&(u=t.clearValue),l.colorAttachments.push({view:h.view,depthSlice:h.depthSlice,resolveTarget:h.resolveTarget,loadOp:t.loadOp||Ce.Load,storeOp:t.storeOp||Ct.Store,clearValue:u})}return a.depthStencilView&&(l.depthStencilAttachment={view:a.depthStencilView}),l}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,n=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=n,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);let r;e.textures===null?r=this._getDefaultRenderPassDescriptor():r=this._getRenderPassDescriptor(e,{loadOp:Ce.Load}),this.initTimestampQuery(e,r),r.occlusionQuerySet=n;const a=r.depthStencilAttachment;if(e.textures!==null){const c=r.colorAttachments;for(let h=0;h<c.length;h++){const u=c[h];e.clearColor?(u.clearValue=h===0?e.clearColorValue:{r:0,g:0,b:0,a:1},u.loadOp=Ce.Clear):u.loadOp=Ce.Load,u.storeOp=Ct.Store}}else{const c=r.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=Ce.Clear):c.loadOp=Ce.Load,c.storeOp=Ct.Store}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=Ce.Clear):a.depthLoadOp=Ce.Load,a.depthStoreOp=Ct.Store),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=Ce.Clear):a.stencilLoadOp=Ce.Load,a.stencilStoreOp=Ct.Store);const l=s.createCommandEncoder({label:"renderContext_"+e.id});if(this._isRenderCameraDepthArray(e)===!0){const c=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==c.length?this._createDepthLayerDescriptors(e,t,r,c):this._updateDepthLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let h=0;h<c.length;h++){const u=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+h),d={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(u),t.bundleSets.push(d)}t.currentPass=null}else{const c=l.beginRenderPass(r);if(t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor){const{x:h,y:u,width:d,height:p}=e.scissorValue;c.setScissorRect(h,u,d,p)}}t.descriptor=r,t.encoder=l,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const n=s.depthStencilAttachment;t.layerDescriptors=[];const r=this.get(e.depthTexture);r.viewCache||(r.viewCache=[]);for(let a=0;a<i.length;a++){const l={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[a].view}]};if(s.depthStencilAttachment){const c=a;r.viewCache[c]||(r.viewCache[c]=r.texture.createView({dimension:ft.TwoD,baseArrayLayer:a,arrayLayerCount:1})),l.depthStencilAttachment={view:r.viewCache[c],depthLoadOp:n.depthLoadOp||Ce.Clear,depthStoreOp:n.depthStoreOp||Ct.Store,depthClearValue:n.depthClearValue||1},e.stencil&&(l.depthStencilAttachment.stencilLoadOp=n.stencilLoadOp,l.depthStencilAttachment.stencilStoreOp=n.stencilStoreOp,l.depthStencilAttachment.stencilClearValue=n.stencilClearValue)}else l.depthStencilAttachment={...n};t.layerDescriptors.push(l)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const n=t.layerDescriptors[i];if(n.depthStencilAttachment){const r=n.depthStencilAttachment;e.depth&&(e.clearDepth?(r.depthClearValue=e.clearDepthValue,r.depthLoadOp=Ce.Clear):r.depthLoadOp=Ce.Load),e.stencil&&(e.clearStencil?(r.stencilClearValue=e.clearStencilValue,r.stencilLoadOp=Ce.Clear):r.stencilLoadOp=Ce.Load)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const n=[];for(let r=0;r<t.bundleEncoders.length;r++){const a=t.bundleEncoders[r];n.push(a.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<n.length){const a=t.layerDescriptors[r],l=i.beginRenderPass(a);if(e.viewport){const{x:c,y:h,width:u,height:d,minDepth:p,maxDepth:f}=e.viewportValue;l.setViewport(c,h,u,d,p,f)}if(e.scissor){const{x:c,y:h,width:u,height:d}=e.scissorValue;l.setScissorRect(c,h,u,d)}l.executeBundles([n[r]]),l.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const n=s*8;let r=this.occludedResolveCache.get(n);r===void 0&&(r=this.device.createBuffer({size:n,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(n,r));const a=this.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,a,0,n),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const n=e.textures;for(let r=0;r<n.length;r++){const a=n[r];a.generateMipmaps===!0&&this.textureUtils.generateMipmaps(a)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),a=new BigUint64Array(r);for(let l=0;l<i.length;l++)a[l]===BigInt(0)&&n.add(i[l]);s.destroy(),t.occluded=n}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:n,height:r,minDepth:a,maxDepth:l}=e.viewportValue;t.setViewport(s,i,n,r,a,l)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const n=this.device,r=this.renderer;let a=[],l,c,h,u;if(e){const f=this.getClearColor();c={r:f.r,g:f.g,b:f.b,a:f.a}}if(i===null){h=r.depth,u=r.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const m=a[0];m.clearValue=c,m.loadOp=Ce.Clear,m.storeOp=Ct.Store}(h||u)&&(l=f.depthStencilAttachment)}else{h=i.depth,u=i.stencil;const f={loadOp:e?Ce.Clear:Ce.Load,clearValue:e?c:void 0};h&&(f.depthLoadOp=t?Ce.Clear:Ce.Load,f.depthClearValue=t?r.getClearDepth():void 0,f.depthStoreOp=Ct.Store),u&&(f.stencilLoadOp=s?Ce.Clear:Ce.Load,f.stencilClearValue=s?r.getClearStencil():void 0,f.stencilStoreOp=Ct.Store);const m=this._getRenderPassDescriptor(i,f);a=m.colorAttachments,l=m.depthStencilAttachment}h&&l&&l.depthLoadOp===void 0&&(t?(l.depthLoadOp=Ce.Clear,l.depthClearValue=r.getClearDepth(),l.depthStoreOp=Ct.Store):(l.depthLoadOp=Ce.Load,l.depthStoreOp=Ct.Store)),u&&l&&l.stencilLoadOp===void 0&&(s?(l.stencilLoadOp=Ce.Clear,l.stencilClearValue=r.getClearStencil(),l.stencilStoreOp=Ct.Store):(l.stencilLoadOp=Ce.Load,l.stencilStoreOp=Ct.Store));const d=n.createCommandEncoder({label:"clear"});d.beginRenderPass({colorAttachments:a,depthStencilAttachment:l}).end(),n.queue.submit([d.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i){const{passEncoderGPU:n}=this.get(e),r=this.get(i).pipeline;this.pipelineUtils.setPipeline(n,r);for(let h=0,u=s.length;h<u;h++){const d=s[h],p=this.get(d);n.setBindGroup(h,p.group)}const a=this.device.limits.maxComputeWorkgroupsPerDimension,l=this.get(t);l.dispatchSize===void 0&&(l.dispatchSize={x:0,y:1,z:1});const{dispatchSize:c}=l;t.dispatchCount>a?(c.x=Math.min(t.dispatchCount,a),c.y=Math.ceil(t.dispatchCount/a)):c.x=t.dispatchCount,n.dispatchWorkgroups(c.x,c.y,c.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,material:i,context:n,pipeline:r}=e,a=e.getBindings(),l=this.get(n),c=this.get(r).pipeline,h=e.getIndex(),u=h!==null,d=e.getDrawParameters();if(d===null)return;const p=(m,y)=>{this.pipelineUtils.setPipeline(m,c),y.pipeline=c;const g=y.bindingGroups;for(let b=0,T=a.length;b<T;b++){const S=a[b],C=this.get(S);g[S.index]!==S.id&&(m.setBindGroup(S.index,C.group),g[S.index]=S.id)}if(u===!0&&y.index!==h){const b=this.get(h).buffer,T=h.array instanceof Uint16Array?mr.Uint16:mr.Uint32;m.setIndexBuffer(b,T),y.index=h}const _=e.getVertexBuffers();for(let b=0,T=_.length;b<T;b++){const S=_[b];if(y.attributes[b]!==S){const C=this.get(S).buffer;m.setVertexBuffer(b,C),y.attributes[b]=S}}n.stencil===!0&&i.stencilWrite===!0&&l.currentStencilRef!==i.stencilRef&&(m.setStencilReference(i.stencilRef),l.currentStencilRef=i.stencilRef)},f=(m,y)=>{if(p(m,y),s.isBatchedMesh===!0){const g=s._multiDrawStarts,_=s._multiDrawCounts,b=s._multiDrawCount,T=s._multiDrawInstances;T!==null&&oi("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let S=0;S<b;S++){const C=T?T[S]:1,w=C>1?0:S;u===!0?m.drawIndexed(_[S],C,g[S]/h.array.BYTES_PER_ELEMENT,0,w):m.draw(_[S],C,g[S],w),t.update(s,_[S],C)}}else if(u===!0){const{vertexCount:g,instanceCount:_,firstVertex:b}=d,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer;m.drawIndexedIndirect(S,0)}else m.drawIndexed(g,_,b,0,0);t.update(s,g,_)}else{const{vertexCount:g,instanceCount:_,firstVertex:b}=d,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer;m.drawIndirect(S,0)}else m.draw(g,_,b,0);t.update(s,g,_)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const m=this.get(e.camera),y=e.camera.cameras,g=e.getBindingGroup("cameraIndex");if(m.indexesGPU===void 0||m.indexesGPU.length!==y.length){const b=this.get(g),T=[],S=new Uint32Array([0,0,0,0]);for(let C=0,w=y.length;C<w;C++){S[0]=C;const R=this.bindingUtils.createBindGroupIndex(S,b.layout);T.push(R)}m.indexesGPU=T}const _=this.renderer.getPixelRatio();for(let b=0,T=y.length;b<T;b++){const S=y[b];if(s.layers.test(S.layers)){const C=S.viewport;let w=l.currentPass,R=l.currentSets;if(l.bundleEncoders){const P=l.bundleEncoders[b],z=l.bundleSets[b];w=P,R=z}C&&w.setViewport(Math.floor(C.x*_),Math.floor(C.y*_),Math.floor(C.width*_),Math.floor(C.height*_),n.viewportValue.minDepth,n.viewportValue.maxDepth),g&&m.indexesGPU&&(w.setBindGroup(g.index,m.indexesGPU[b]),R.bindingGroups[g.index]=g.id),f(w,R)}}}else if(l.currentPass){if(l.occlusionQuerySet!==void 0){const m=l.lastOcclusionObject;m!==s&&(m!==null&&m.occlusionTest===!0&&(l.currentPass.endOcclusionQuery(),l.occlusionQueryIndex++),s.occlusionTest===!0&&(l.currentPass.beginOcclusionQuery(l.occlusionQueryIndex),l.occlusionQueryObjects[l.occlusionQueryIndex]=s),l.lastOcclusionObject=s)}f(l.currentPass,l.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,n=this.utils,r=n.getSampleCountRenderContext(e.context),a=n.getCurrentColorSpace(e.context),l=n.getCurrentColorFormat(e.context),c=n.getCurrentDepthStencilFormat(e.context),h=n.getPrimitiveTopology(s,i);let u=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==r||t.colorSpace!==a||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==h||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=r,t.colorSpace=a,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=h,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,n=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(n),i.getCurrentColorSpace(n),i.getCurrentColorFormat(n),i.getCurrentDepthStencilFormat(n),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=e.isComputeNode?"compute":"render";this.timestampQueryPool[s]||(this.timestampQueryPool[s]=new $A(this.device,s,2048));const i=this.timestampQueryPool[s],n=i.allocateQueriesForContext(e);t.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:n,endOfPassWriteIndex:n+1}}createNodeBuilder(e,t){return new LA(e,t)}createProgram(e){const t=this.get(e);t.module={module:this.device.createShaderModule({code:e.code,label:e.stage+(e.name!==""?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),n=s.currentPass.finish();this.get(t).bundleGPU=n,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){let a=0,l=0,c=0,h=0,u=0,d=0,p=e.image.width,f=e.image.height,m=1;s!==null&&(s.isBox3===!0?(h=s.min.x,u=s.min.y,d=s.min.z,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=s.max.z-s.min.z):(h=s.min.x,u=s.min.y,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=1)),i!==null&&(a=i.x,l=i.y,c=i.z||0);const y=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;y.copyTextureToTexture({texture:g,mipLevel:n,origin:{x:h,y:u,z:d}},{texture:_,mipLevel:r,origin:{x:a,y:l,z:c}},[p,f,m]),this.device.queue.submit([y.finish()]),r===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let n=null;t.renderTarget?e.isDepthTexture?n=this.get(t.depthTexture).texture:n=this.get(t.textures[0]).texture:e.isDepthTexture?n=this.textureUtils.getDepthBuffer(t.depth,t.stencil):n=this.context.getCurrentTexture();const r=this.get(e).texture;if(n.format!==r.format){console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,r.format);return}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:n,origin:[s.x,s.y,0]},{texture:r},[s.z,s.w]),i.currentPass){const{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=Ce.Load;if(t.depth&&(l.depthStencilAttachment.depthLoadOp=Ce.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=Ce.Load),i.currentPass=a.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:c,y:h,width:u,height:d}=t.scissorValue;i.currentPass.setScissorRect(c,h,u,d)}}else this.device.queue.submit([a.finish()]);e.generateMipmaps&&this.textureUtils.generateMipmaps(e)}}class qA extends Gt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ve(16777215),this.specular=new ve(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.combine=hl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.flatShading=e.flatShading,this.fog=e.fog,this}}const YA=new qA;class XA extends it{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(YA),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Wu(t):null}setupLightingModel(){return new My}setupVariants(){const e=(this.shininessNode?B(this.shininessNode):Hv).max(1e-4);Lh.assign(e);const t=this.specularNode||$v;Yt.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}class Uy extends Gt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new ve(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}const ZA=new Uy;class ky extends it{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(ZA),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new hE(t):null}setupLightingModel(){return new Ey}setupSpecular(){const e=Ve(I(.04),Se.rgb,il);Yt.assign(e),rl.assign(1)}setupVariants(){const e=this.metalnessNode?B(this.metalnessNode):Yv;il.assign(e);let t=this.roughnessNode?B(this.roughnessNode):qv;t=my({roughness:t}),Xs.assign(t),this.setupSpecular(),Se.assign(ne(Se.rgb.mul(e.oneMinus()),Se.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}class QA extends Uy{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new ce(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return pe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ve(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new ve(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ve(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}const KA=new QA;class JA extends ky{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(KA),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){const e=this.iorNode?B(this.iorNode):lw;Da.assign(e),Yt.assign(Ve(dr(wg(Da.sub(1).div(Da.add(1))).mul(jv),I(1)).mul(yp),Se.rgb,il)),rl.assign(Ve(yp,1,il))}setupLightingModel(){return new Ey(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?B(this.clearcoatNode):Zv,s=this.clearcoatRoughnessNode?B(this.clearcoatRoughnessNode):Qv;Bh.assign(t),nl.assign(my({roughness:s}))}if(this.useSheen){const t=this.sheenNode?I(this.sheenNode):ew,s=this.sheenRoughnessNode?B(this.sheenRoughnessNode):tw;Yn.assign(t),bu.assign(s)}if(this.useIridescence){const t=this.iridescenceNode?B(this.iridescenceNode):iw,s=this.iridescenceIORNode?B(this.iridescenceIORNode):nw,i=this.iridescenceThicknessNode?B(this.iridescenceThicknessNode):rw;Tu.assign(t),cg.assign(s),hg.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?H(this.anisotropyNode):sw).toVar();tn.assign(t.length()),Ze(tn.equal(0),()=>{t.assign(H(1,0))}).Else(()=>{t.divAssign(H(tn)),tn.assign(tn.saturate())}),Ih.assign(tn.pow2().mix(Xs.pow2(),1)),Fa.assign(eo[0].mul(t.x).add(eo[1].mul(t.y))),ir.assign(eo[1].mul(t.x).sub(eo[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?B(this.transmissionNode):ow,s=this.thicknessNode?B(this.thicknessNode):aw,i=this.attenuationDistanceNode?B(this.attenuationDistanceNode):cw,n=this.attenuationColorNode?I(this.attenuationColorNode):hw;if(Uh.assign(t),ug.assign(s),dg.assign(i),pg.assign(n),this.useDispersion){const r=this.dispersionNode?B(this.dispersionNode):gw;fg.assign(r)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?I(this.clearcoatNormalNode):Kv}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const eR=L(({normal:o,lightDirection:e,builder:t})=>{const s=o.dot(e),i=H(s.mul(.5).add(.5),0);if(t.material.gradientMap){const n=Ei("gradientMap","texture").context({getUV:()=>i});return I(n.r)}else{const n=i.fwidth().mul(.5);return Ve(I(.7),I(1),Bi(B(.7).sub(n.x),B(.7).add(n.x),i.x))}});class tR extends El{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const n=eR({normal:kg,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(n.mul(fr({diffuseColor:Se.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(fr({diffuseColor:Se}))),i.indirectDiffuse.mulAssign(t)}}class sR extends Gt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ve(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const iR=new sR;class nR extends it{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(iR),this.setValues(e)}setupLightingModel(){return new tR}}class rR extends _r{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=B(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}const oR=new Ai;class aR extends it{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(oR),this.setValues(e)}setupNormal(){return zs}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Wu(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new rR(Jg)),t}setupOutgoingLight(){return Se.rgb}setupLightingModel(){return new wy}}class lR extends Gt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ve(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.combine=hl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.flatShading=e.flatShading,this.fog=e.fog,this}}const cR=new lR;class hR extends it{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(cR),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Wu(t):null}setupLightingModel(){return new My(!1)}}class uR extends Gt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const dR=new uR;class pR extends it{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(dR),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?B(this.opacityNode):Kg;Se.assign(Au(ne(cv(et),e),Xt))}}class fR extends Gt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ve(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new ce(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}const mR=new fR;class gR extends it{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(mR),this.setValues(e)}setupVariants(e){const t=ov;let s;e.material.matcap?s=Ei("matcap","texture").context({getUV:()=>t}):s=I(Ve(.2,.8,t.y)),Se.rgb.mulAssign(s.rgb)}}class zy extends Gt{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ve(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}}const yR=new zy;class xR extends it{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(yR),this.setValues(e)}}class _R extends zy{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const bR=new _R;class TR extends it{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(bR),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?B(this.offsetNode):fw,t=this.dashScaleNode?B(this.dashScaleNode):uw,s=this.dashSizeNode?B(this.dashSizeNode):dw,i=this.gapSizeNode?B(this.gapSizeNode):pw;Zl.assign(s),op.assign(i);const n=ws(Ii("lineDistance").mul(t));(e?n.add(e):n).mod(Zl.add(op)).greaterThan(Zl).discard()}}class SR extends Gt{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ve(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!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.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const vR=new SR;class Vy extends it{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(vR),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:n,rotationNode:r,scaleNode:a}=this,l=_l.mul(I(n||0));let c=H(dn[0].xyz.length(),dn[1].xyz.length());if(a!==null&&(c=c.mul(H(a))),i===!1)if(s.isPerspectiveCamera)c=c.mul(l.z.negate());else{const p=B(2).div(Fu.element(1).element(1));c=c.mul(p.mul(2))}let h=bl.xy;if(t.center&&t.center.isVector2===!0){const p=_S("center","vec2",t);h=h.sub(p.sub(.5))}h=h.mul(c);const u=B(r||Jv),d=Vg(h,u);return ne(l.xy.add(d),l.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}class wR extends Gt{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new ve(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}}const MR=new wR;class CR extends Vy{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(MR),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return _l.mul(I(e||bt)).xyz}setupVertex(e){const t=super.setupVertex(e);if(e.material.isNodeMaterial!==!0)return t;const{rotationNode:s,scaleNode:i,sizeNode:n}=this,r=bl.xy.toVar(),a=ho.z.div(ho.w);if(s&&s.isNode){const c=B(s);r.assign(Vg(r,c))}let l=n!==null?H(n):mw;return this.sizeAttenuation===!0&&(l=l.mul(l.div(st.z.negate()))),i&&i.isNode&&(l=l.mul(H(i))),r.mulAssign(l.mul(2)),r.assign(r.div(ho.z)),r.y.assign(r.y.mul(a)),r.assign(r.mul(t.w)),t.addAssign(ne(r,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class ER extends El{constructor(){super(),this.shadowNode=B(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Se.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Se.rgb)}}class AR extends Gt{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new ve(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}const RR=new AR;class NR extends it{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(RR),this.setValues(e)}setupLightingModel(){return new ER}}class gn extends dt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new ve(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}const qc=new Ie,Pf=new N,Ff=new N;class Qu{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ce(512,512),this.mapType=Nt,this.map=null,this.mapPass=null,this.matrix=new Ie,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Yu,this._frameExtents=new ce(1,1),this._viewportCount=1,this._viewports=[new ge(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Pf.setFromMatrixPosition(e.matrixWorld),t.position.copy(Pf),Ff.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Ff),t.updateMatrixWorld(),qc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(qc),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(qc)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const Df=new Ie,Gr=new N,Yc=new N;class PR extends Qu{constructor(){super(new Zt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new ce(4,2),this._viewportCount=6,this._viewports=[new ge(2,1,1,1),new ge(0,1,1,1),new ge(3,1,1,1),new ge(1,1,1,1),new ge(3,0,1,1),new ge(1,0,1,1)],this._cubeDirections=[new N(1,0,0),new N(-1,0,0),new N(0,0,1),new N(0,0,-1),new N(0,1,0),new N(0,-1,0)],this._cubeUps=[new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,0,1),new N(0,0,-1)]}updateMatrices(e,t=0){const s=this.camera,i=this.matrix,n=e.distance||s.far;n!==s.far&&(s.far=n,s.updateProjectionMatrix()),Gr.setFromMatrixPosition(e.matrixWorld),s.position.copy(Gr),Yc.copy(s.position),Yc.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(Yc),s.updateMatrixWorld(),i.makeTranslation(-Gr.x,-Gr.y,-Gr.z),Df.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Df)}}class FR extends gn{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new PR}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class DR extends Qu{constructor(){super(new Lu(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class OR extends gn{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.target=new dt,this.shadow=new DR}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class BR extends gn{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class IR extends Qu{constructor(){super(new Zt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=ar*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,n=e.distance||t.far;(s!==t.fov||i!==t.aspect||n!==t.far)&&(t.fov=s,t.aspect=i,t.far=n,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Ku extends gn{constructor(e,t,s=0,i=Math.PI/3,n=0,r=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.target=new dt,this.distance=s,this.angle=i,this.penumbra=n,this.decay=r,this.map=null,this.shadow=new IR}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class LR extends gn{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class UR extends gn{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ve(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}class kR{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new N)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,n=e.z,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.282095),t.addScaledVector(r[1],.488603*i),t.addScaledVector(r[2],.488603*n),t.addScaledVector(r[3],.488603*s),t.addScaledVector(r[4],1.092548*(s*i)),t.addScaledVector(r[5],1.092548*(i*n)),t.addScaledVector(r[6],.315392*(3*n*n-1)),t.addScaledVector(r[7],1.092548*(s*n)),t.addScaledVector(r[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,n=e.z,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.886227),t.addScaledVector(r[1],2*.511664*i),t.addScaledVector(r[2],2*.511664*n),t.addScaledVector(r[3],2*.511664*s),t.addScaledVector(r[4],2*.429043*s*i),t.addScaledVector(r[5],2*.429043*i*n),t.addScaledVector(r[6],.743125*n*n-.247708),t.addScaledVector(r[7],2*.429043*s*n),t.addScaledVector(r[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){const s=e.x,i=e.y,n=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*n,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*n,t[6]=.315392*(3*n*n-1),t[7]=1.092548*s*n,t[8]=.546274*(s*s-i*i)}}class zR extends gn{constructor(e=new kR,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class VR extends Ku{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class GR extends Ku{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class HR extends Ay{constructor(){super(),this.addMaterial(XA,"MeshPhongMaterial"),this.addMaterial(ky,"MeshStandardMaterial"),this.addMaterial(JA,"MeshPhysicalMaterial"),this.addMaterial(nR,"MeshToonMaterial"),this.addMaterial(aR,"MeshBasicMaterial"),this.addMaterial(hR,"MeshLambertMaterial"),this.addMaterial(pR,"MeshNormalMaterial"),this.addMaterial(gR,"MeshMatcapMaterial"),this.addMaterial(xR,"LineBasicMaterial"),this.addMaterial(TR,"LineDashedMaterial"),this.addMaterial(CR,"PointsMaterial"),this.addMaterial(Vy,"SpriteMaterial"),this.addMaterial(NR,"ShadowMaterial"),this.addLight(YM,FR),this.addLight(sE,OR),this.addLight(iE,BR),this.addLight(Hu,Ku),this.addLight(aE,LR),this.addLight(lE,UR),this.addLight(cE,zR),this.addLight(nE,VR),this.addLight(oE,GR),this.addToneMapping(sM,l_),this.addToneMapping(iM,c_),this.addToneMapping(nM,h_),this.addToneMapping(oM,u_),this.addToneMapping(hM,d_),this.addToneMapping(uM,p_)}}class ya extends ZE{constructor(e={}){let t;e.forceWebGL?t=vf:(t=jA,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new vf(e)));const s=new t(e);super(s,e),this.library=new HR,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class WR extends x.Line{constructor(e,t){const s=[1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],i=new x.BufferGeometry;i.setAttribute("position",new x.Float32BufferAttribute(s,3)),i.computeBoundingSphere();const n=new x.LineBasicMaterial({fog:!1});super(i,n),this.light=e,this.color=t,this.type="RectAreaLightHelper";const r=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],a=new x.BufferGeometry;a.setAttribute("position",new x.Float32BufferAttribute(r,3)),a.computeBoundingSphere(),this.add(new x.Mesh(a,new x.MeshBasicMaterial({side:x.BackSide,fog:!1})))}updateMatrixWorld(){if(this.scale.set(.5*this.light.width,.5*this.light.height,1),this.color!==void 0)this.material.color.set(this.color),this.children[0].material.color.set(this.color);else{this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);const e=this.material.color,t=Math.max(e.r,e.g,e.b);t>1&&e.multiplyScalar(1/t),this.children[0].material.color.copy(this.material.color)}this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld),this.children[0].matrixWorld.copy(this.matrixWorld)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const Of={type:"change"},Ju={type:"start"},Gy={type:"end"},xa=new x.Ray,Bf=new x.Plane,$R=Math.cos(70*x.MathUtils.DEG2RAD),lt=new x.Vector3,It=2*Math.PI,Fe={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Xc=1e-6;class jR extends x.Controls{constructor(e,t=null){super(e,t),this.state=Fe.NONE,this.target=new x.Vector3,this.cursor=new x.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:x.MOUSE.ROTATE,MIDDLE:x.MOUSE.DOLLY,RIGHT:x.MOUSE.PAN},this.touches={ONE:x.TOUCH.ROTATE,TWO:x.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new x.Vector3,this._lastQuaternion=new x.Quaternion,this._lastTargetPosition=new x.Vector3,this._quat=new x.Quaternion().setFromUnitVectors(e.up,new x.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new x.Spherical,this._sphericalDelta=new x.Spherical,this._scale=1,this._panOffset=new x.Vector3,this._rotateStart=new x.Vector2,this._rotateEnd=new x.Vector2,this._rotateDelta=new x.Vector2,this._panStart=new x.Vector2,this._panEnd=new x.Vector2,this._panDelta=new x.Vector2,this._dollyStart=new x.Vector2,this._dollyEnd=new x.Vector2,this._dollyDelta=new x.Vector2,this._dollyDirection=new x.Vector3,this._mouse=new x.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=YR.bind(this),this._onPointerDown=qR.bind(this),this._onPointerUp=XR.bind(this),this._onContextMenu=sN.bind(this),this._onMouseWheel=KR.bind(this),this._onKeyDown=JR.bind(this),this._onTouchStart=eN.bind(this),this._onTouchMove=tN.bind(this),this._onMouseDown=ZR.bind(this),this._onMouseMove=QR.bind(this),this._interceptControlDown=iN.bind(this),this._interceptControlUp=nN.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Of),this.update(),this.state=Fe.NONE}update(e=null){const t=this.object.position;lt.copy(t).sub(this.target),lt.applyQuaternion(this._quat),this._spherical.setFromVector3(lt),this.autoRotate&&this.state===Fe.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let s=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(s)&&isFinite(i)&&(s<-Math.PI?s+=It:s>Math.PI&&(s-=It),i<-Math.PI?i+=It:i>Math.PI&&(i-=It),s<=i?this._spherical.theta=Math.max(s,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(s+i)/2?Math.max(s,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=r!=this._spherical.radius}if(lt.setFromSpherical(this._spherical),lt.applyQuaternion(this._quatInverse),t.copy(this.target).add(lt),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=lt.length();r=this._clampDistance(a*this._scale);const l=a-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),n=!!l}else if(this.object.isOrthographicCamera){const a=new x.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=l!==this.object.zoom;const c=new x.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),r=lt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(xa.origin.copy(this.object.position),xa.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(xa.direction))<$R?this.object.lookAt(this.target):(Bf.setFromNormalAndCoplanarPoint(this.object.up,this.target),xa.intersectPlane(Bf,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>Xc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Xc||this._lastTargetPosition.distanceToSquared(this.target)>Xc?(this.dispatchEvent(Of),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?It/60*this.autoRotateSpeed*e:It/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){lt.setFromMatrixColumn(t,0),lt.multiplyScalar(-e),this._panOffset.add(lt)}_panUp(e,t){this.screenSpacePanning===!0?lt.setFromMatrixColumn(t,1):(lt.setFromMatrixColumn(t,0),lt.crossVectors(this.object.up,lt)),lt.multiplyScalar(e),this._panOffset.add(lt)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;lt.copy(i).sub(this.target);let n=lt.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*n/s.clientHeight,this.object.matrix),this._panUp(2*t*n/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,n=t-s.top,r=s.width,a=s.height;this._mouse.x=i/r*2-1,this._mouse.y=-(n/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(It*this._rotateDelta.x/t.clientHeight),this._rotateUp(It*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const s=this._getSecondPointerPosition(e),i=.5*(e.pageX+s.x),n=.5*(e.pageY+s.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(It*this._rotateDelta.x/t.clientHeight),this._rotateUp(It*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,n),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new x.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function qR(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function YR(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function XR(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Gy),this.state=Fe.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function ZR(o){let e;switch(o.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case x.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=Fe.DOLLY;break;case x.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=Fe.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=Fe.ROTATE}break;case x.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=Fe.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=Fe.PAN}break;default:this.state=Fe.NONE}this.state!==Fe.NONE&&this.dispatchEvent(Ju)}function QR(o){switch(this.state){case Fe.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case Fe.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case Fe.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function KR(o){this.enabled===!1||this.enableZoom===!1||this.state!==Fe.NONE||(o.preventDefault(),this.dispatchEvent(Ju),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(Gy))}function JR(o){this.enabled!==!1&&this._handleKeyDown(o)}function eN(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case x.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=Fe.TOUCH_ROTATE;break;case x.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=Fe.TOUCH_PAN;break;default:this.state=Fe.NONE}break;case 2:switch(this.touches.TWO){case x.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=Fe.TOUCH_DOLLY_PAN;break;case x.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=Fe.TOUCH_DOLLY_ROTATE;break;default:this.state=Fe.NONE}break;default:this.state=Fe.NONE}this.state!==Fe.NONE&&this.dispatchEvent(Ju)}function tN(o){switch(this._trackPointer(o),this.state){case Fe.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case Fe.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case Fe.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case Fe.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=Fe.NONE}}function sN(o){this.enabled!==!1&&o.preventDefault()}function iN(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function nN(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}/*!
|
|
480
|
+
var<${s}> ${e} : ${r};`}}class lR{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=M.Depth24PlusStencil8:e.depth&&(t=M.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const n=this.backend.renderer,r=n.getRenderTarget();t=r?r.samples:n.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return Kn.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return Kn.LineList;if(e.isLine)return Kn.LineStrip;if(e.isMesh)return Kn.TriangleList}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),t===2&&(t=4)),t}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(e===void 0)return navigator.gpu.getPreferredCanvasFormat();if(e===Nt)return M.BGRA8Unorm;if(e===rs)return M.RGBA16Float;throw new Error("Unsupported outputType")}}const cR=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),hR=new Map([[eg,["float16"]]]),uR=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class dR{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,n=i.get(s);let r=n.buffer;if(r===void 0){const a=i.device;let l=s.array;if(e.normalized===!1){if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let u=0;u<l.length;u++)l[u]===65535&&(l[u]=4294967295)}if(s.array=l,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&s.itemSize===3){l=new l.constructor(s.count*4);for(let u=0;u<s.count;u++)l.set(s.array.subarray(u*3,u*3+3),u*4);s.itemSize=4,s.array=l,n._force3to4BytesAlignment=!0}const c=l.byteLength,h=c+(4-c%4)%4;r=a.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new l.constructor(r.getMappedRange()).set(l),r.unmap(),n.buffer=r}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,n=s.get(t),r=s.get(t).buffer;let a=t.array;if(n._force3to4BytesAlignment===!0){a=new a.constructor(t.count*4);for(let h=0;h<t.count;h++)a.set(t.array.subarray(h*3,h*3+3),h*4);t.array=a}const l=this._isTypedArray(a),c=t.updateRanges;if(c.length===0)i.queue.writeBuffer(r,0,a,0);else{const h=l?1:a.BYTES_PER_ELEMENT;for(let u=0,d=c.length;u<d;u++){const p=c[u];let f,m;if(n._force3to4BytesAlignment===!0){const g=Math.floor(p.start/3),_=Math.ceil(p.count/3);f=g*4*h,m=_*4*h}else f=p.start*h,m=p.count*h;const x=f*(l?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(r,x,a,f,m)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let i=0;i<t.length;i++){const n=t[i],r=n.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(n);let l=s.get(a);if(l===void 0){let u,d;n.isInterleavedBufferAttribute===!0?(u=n.data.stride*r,d=n.data.isInstancedInterleavedBuffer?ga.Instance:ga.Vertex):(u=n.itemSize*r,d=n.isInstancedBufferAttribute?ga.Instance:ga.Vertex),n.normalized===!1&&(n.array.constructor===Int16Array||n.array.constructor===Uint16Array)&&(u=4),l={arrayStride:u,attributes:[],stepMode:d},s.set(a,l)}const c=this._getVertexFormat(n),h=n.isInterleavedBufferAttribute===!0?n.offset*r:0;l.attributes.push({shaderLocation:i,offset:h,format:c})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,n=t.get(this._getBufferAttribute(e)).buffer,r=n.size,a=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),l=s.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(n,0,a,0,r);const c=l.finish();s.queue.submit([c]),await a.mapAsync(GPUMapMode.READ);const h=a.getMappedRange(),u=new e.array.constructor(h.slice(0));return a.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,n=e.constructor;let r;if(t===1)r=uR.get(i);else{const l=(hR.get(n)||cR.get(i))[s?1:0];if(l){const c=i.BYTES_PER_ELEMENT*t,u=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(u%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");r=`${l}x${u}`}}return r||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),r}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class pR{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,s=t.device,i=[];let n=0;for(const r of e.bindings){const a={binding:n++,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const l={};r.isStorageBuffer&&(r.visibility&4&&(r.access===Zs.READ_WRITE||r.access===Zs.WRITE_ONLY)?l.type=Yc.Storage:l.type=Yc.ReadOnlyStorage),a.buffer=l}else if(r.isSampler){const l={};r.texture.isDepthTexture&&(r.texture.compareFunction!==null?l.type=Af.Comparison:t.compatibilityMode&&(l.type=Af.NonFiltering)),a.sampler=l}else if(r.isSampledTexture&&r.texture.isVideoTexture)a.externalTexture={};else if(r.isSampledTexture&&r.store){const l={};l.format=this.backend.get(r.texture).texture.format;const c=r.access;c===Zs.READ_WRITE?l.access=Xc.ReadWrite:c===Zs.WRITE_ONLY?l.access=Xc.WriteOnly:l.access=Xc.ReadOnly,a.storageTexture=l}else if(r.isSampledTexture){const l={},{primarySamples:c}=t.utils.getTextureSampleData(r.texture);if(c>1&&(l.multisampled=!0,r.texture.isDepthTexture||(l.sampleType=Yi.UnfilterableFloat)),r.texture.isDepthTexture)t.compatibilityMode&&r.texture.compareFunction===null?l.sampleType=Yi.UnfilterableFloat:l.sampleType=Yi.Depth;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const h=r.texture.type;h===Et?l.sampleType=Yi.SInt:h===Xe?l.sampleType=Yi.UInt:h===Kt&&(this.backend.hasFeature("float32-filterable")?l.sampleType=Yi.Float:l.sampleType=Yi.UnfilterableFloat)}r.isSampledCubeTexture?l.viewDimension=ft.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?l.viewDimension=ft.TwoDArray:r.isSampledTexture3D&&(l.viewDimension=ft.ThreeD),a.texture=l}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);i.push(a)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,s,i=0){const{backend:n,bindGroupLayoutCache:r}=this,a=n.get(e);let l=r.get(e.bindingsReference);l===void 0&&(l=this.createBindingsLayout(e),r.set(e.bindingsReference,l));let c;s>0&&(a.groups===void 0&&(a.groups=[],a.versions=[]),a.versions[s]===i&&(c=a.groups[s])),c===void 0&&(c=this.createBindGroup(e,l),s>0&&(a.groups[s]=c,a.versions[s]=i)),a.group=c,a.layout=l}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,n=t.get(e).buffer;s.queue.writeBuffer(n,0,i,0)}createBindGroupIndex(e,t){const i=this.backend.device,n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],a=i.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:n});i.queue.writeBuffer(a,0,e,0);const l=[{binding:0,resource:{buffer:a}}];return i.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:l})}createBindGroup(e,t){const s=this.backend,i=s.device;let n=0;const r=[];for(const a of e.bindings){if(a.isUniformBuffer){const l=s.get(a);if(l.buffer===void 0){const c=a.byteLength,h=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,u=i.createBuffer({label:"bindingBuffer_"+a.name,size:c,usage:h});l.buffer=u}r.push({binding:n,resource:{buffer:l.buffer}})}else if(a.isStorageBuffer){const l=s.get(a);if(l.buffer===void 0){const c=a.attribute;l.buffer=s.get(c).buffer}r.push({binding:n,resource:{buffer:l.buffer}})}else if(a.isSampler){const l=s.get(a.texture);r.push({binding:n,resource:l.sampler})}else if(a.isSampledTexture){const l=s.get(a.texture);let c;if(l.externalTexture!==void 0)c=i.importExternalTexture({source:l.externalTexture});else{const h=a.store?1:l.texture.mipLevelCount,u=`view-${l.texture.width}-${l.texture.height}-${h}`;if(c=l[u],c===void 0){const d=HA.All;let p;a.isSampledCubeTexture?p=ft.Cube:a.isSampledTexture3D?p=ft.ThreeD:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?p=ft.TwoDArray:p=ft.TwoD,c=l[u]=l.texture.createView({aspect:d,dimension:p,mipLevelCount:h})}}r.push({binding:n,resource:c})}n++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:r})}}class fR{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:n,pipeline:r}=e,{vertexProgram:a,fragmentProgram:l}=r,c=this.backend,h=c.device,u=c.utils,d=c.get(r),p=[];for(const j of e.getBindings()){const X=c.get(j);p.push(X.layout)}const f=c.attributeUtils.createShaderVertexBuffers(e);let m;i.blending!==hr&&(i.blending!==Js||i.transparent!==!1)&&(m=this._getBlending(i));let x={};i.stencilWrite===!0&&(x={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(e.context.textures!==null){const j=e.context.textures;for(let X=0;X<j.length;X++){const Z=u.getTextureFormatGPU(j[X]);_.push({format:Z,blend:m,writeMask:g})}}else{const j=u.getCurrentColorFormat(e.context);_.push({format:j,blend:m,writeMask:g})}const b=c.get(a).module,T=c.get(l).module,S=this._getPrimitiveState(s,n,i),C=this._getDepthCompare(i),w=u.getCurrentDepthStencilFormat(e.context),R=this._getSampleCount(e.context),P={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:f}),fragment:Object.assign({},T,{targets:_}),primitive:S,multisample:{count:R,alphaToCoverageEnabled:i.alphaToCoverage&&R>1},layout:h.createPipelineLayout({bindGroupLayouts:p})},z={},$=e.context.depth,q=e.context.stencil;if(($===!0||q===!0)&&($===!0&&(z.format=w,z.depthWriteEnabled=i.depthWrite,z.depthCompare=C),q===!0&&(z.stencilFront=x,z.stencilBack={},z.stencilReadMask=i.stencilFuncMask,z.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&(z.depthBias=i.polygonOffsetUnits,z.depthBiasSlopeScale=i.polygonOffsetFactor,z.depthBiasClamp=0),P.depthStencil=z),t===null)d.pipeline=h.createRenderPipeline(P);else{const j=new Promise(X=>{h.createRenderPipelineAsync(P).then(Z=>{d.pipeline=Z,X()})});t.push(j)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:n}=s,r=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormat(e),l=this._getSampleCount(e),c={label:t,colorFormats:[a],depthStencilFormat:r,sampleCount:l};return n.createRenderBundleEncoder(c)}createComputePipeline(e,t){const s=this.backend,i=s.device,n=s.get(e.computeProgram).module,r=s.get(e),a=[];for(const l of t){const c=s.get(l);a.push(c.layout)}r.pipeline=i.createComputePipeline({compute:n,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,s;const i=e.blending,n=e.blendSrc,r=e.blendDst,a=e.blendEquation;if(i===lo){const l=e.blendSrcAlpha!==null?e.blendSrcAlpha:n,c=e.blendDstAlpha!==null?e.blendDstAlpha:r,h=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(n),dstFactor:this._getBlendFactor(r),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(h)}}else{const l=e.premultipliedAlpha,c=(h,u,d,p)=>{t={srcFactor:h,dstFactor:u,operation:qi.Add},s={srcFactor:d,dstFactor:p,operation:qi.Add}};if(l)switch(i){case Js:c(ie.One,ie.OneMinusSrcAlpha,ie.One,ie.OneMinusSrcAlpha);break;case $a:c(ie.One,ie.One,ie.One,ie.One);break;case ja:c(ie.Zero,ie.OneMinusSrc,ie.Zero,ie.One);break;case qa:c(ie.Zero,ie.Src,ie.Zero,ie.SrcAlpha);break}else switch(i){case Js:c(ie.SrcAlpha,ie.OneMinusSrcAlpha,ie.One,ie.OneMinusSrcAlpha);break;case $a:c(ie.SrcAlpha,ie.One,ie.SrcAlpha,ie.One);break;case ja:c(ie.Zero,ie.OneMinusSrc,ie.Zero,ie.One);break;case qa:c(ie.Zero,ie.Src,ie.Zero,ie.Src);break}}if(t!==void 0&&s!==void 0)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case vi:t=ie.Zero;break;case vm:t=ie.One;break;case wm:t=ie.Src;break;case Mm:t=ie.OneMinusSrc;break;case Ya:t=ie.SrcAlpha;break;case Xa:t=ie.OneMinusSrcAlpha;break;case Am:t=ie.Dst;break;case Rm:t=ie.OneMinusDst;break;case Cm:t=ie.DstAlpha;break;case Em:t=ie.OneMinusDstAlpha;break;case Nm:t=ie.SrcAlphaSaturated;break;case yb:t=ie.Constant;break;case xb:t=ie.OneMinusConstant;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case K_:t=gt.Never;break;case Oh:t=gt.Always;break;case Q_:t=gt.Less;break;case eb:t=gt.LessEqual;break;case J_:t=gt.Equal;break;case ib:t=gt.GreaterEqual;break;case tb:t=gt.Greater;break;case sb:t=gt.NotEqual;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case en:t=_i.Keep;break;case W_:t=_i.Zero;break;case $_:t=_i.Replace;break;case Z_:t=_i.Invert;break;case j_:t=_i.IncrementClamp;break;case q_:t=_i.DecrementClamp;break;case Y_:t=_i.IncrementWrap;break;case X_:t=_i.DecrementWrap;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case bs:t=qi.Add;break;case Tm:t=qi.Subtract;break;case Sm:t=qi.ReverseSubtract;break;case A_:t=qi.Min;break;case R_:t=qi.Max;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},n=this.backend.utils;switch(i.topology=n.getPrimitiveTopology(e,s),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?yr.Uint16:yr.Uint32),s.side){case Qs:i.frontFace=$c.CCW,i.cullMode=jc.Back;break;case Gt:i.frontFace=$c.CCW,i.cullMode=jc.Front;break;case Jn:i.frontFace=$c.CCW,i.cullMode=jc.None;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side);break}return i}_getColorWriteMask(e){return e.colorWrite===!0?Ef.All:Ef.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=gt.Always;else{const s=e.depthFunc;switch(s){case Pm:t=gt.Never;break;case Fm:t=gt.Always;break;case Dm:t=gt.Less;break;case Za:t=gt.LessEqual;break;case Om:t=gt.Equal;break;case Bm:t=gt.GreaterEqual;break;case Im:t=gt.Greater;break;case Lm:t=gt.NotEqual;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class mR extends zy{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return oi(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const n=i.finish();if(this.device.queue.submit([n]),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const r=new BigUint64Array(this.resultBuffer.getMappedRange(0,s));let a=0;for(const[,l]of e){const c=r[l],h=r[l+1],u=Number(h-c)/1e6;a+=u}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class gR extends ky{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.compatibilityMode=e.compatibilityMode===void 0?!1:e.compatibilityMode,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new lR(this),this.attributeUtils=new dR(this),this.bindingUtils=new pR(this),this.pipelineUtils=new fR(this),this.textureUtils=new QA(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(t.device===void 0){const r={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},a=typeof navigator<"u"?await navigator.gpu.requestAdapter(r):null;if(a===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const l=Object.values(qh),c=[];for(const u of l)a.features.has(u)&&c.push(u);const h={requiredFeatures:c,requiredLimits:t.requiredLimits};s=await a.requestDevice(h)}else s=t.device;s.lost.then(r=>{const a={api:"WebGPU",message:r.message||"Unknown reason",reason:r.reason||null,originalEvent:r};e.onDeviceLost(a)});const i=t.context!==void 0?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const n=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(qh.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n}),this.updateSize()}get coordinateSystem(){return Oi}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(e===null){const s=this.renderer;e={colorAttachments:[{view:null}]},(this.renderer.depth===!0||this.renderer.stencil===!0)&&(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(s.depth,s.stencil).createView()});const i=e.colorAttachments[0];this.renderer.samples>0?i.view=this.colorBuffer.createView():i.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let n=i.descriptors;if(n===void 0||i.width!==s.width||i.height!==s.height||i.dimensions!==s.dimensions||i.activeMipmapLevel!==e.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples){n={},i.descriptors=n;const c=()=>{s.removeEventListener("dispose",c),this.delete(s)};s.hasEventListener("dispose",c)===!1&&s.addEventListener("dispose",c)}const r=e.getCacheKey();let a=n[r];if(a===void 0){const c=e.textures,h=[];let u;const d=this._isRenderCameraDepthArray(e);for(let p=0;p<c.length;p++){const f=this.get(c[p]),m={label:`colorAttachment_${p}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:ft.TwoD};if(s.isRenderTarget3D)u=e.activeCubeFace,m.baseArrayLayer=0,m.dimension=ft.ThreeD,m.depthOrArrayLayers=c[p].image.depth;else if(s.isRenderTarget&&c[p].image.depth>1)if(d===!0){const x=e.camera.cameras;for(let g=0;g<x.length;g++){const _={...m,baseArrayLayer:g,arrayLayerCount:1,dimension:ft.TwoD},b=f.texture.createView(_);h.push({view:b,resolveTarget:void 0,depthSlice:void 0})}}else m.dimension=ft.TwoDArray,m.depthOrArrayLayers=c[p].image.depth;if(d!==!0){const x=f.texture.createView(m);let g,_;f.msaaTexture!==void 0?(g=f.msaaTexture.createView(),_=x):(g=x,_=void 0),h.push({view:g,resolveTarget:_,depthSlice:u})}}if(a={textureViews:h},e.depth){const p=this.get(e.depthTexture),f={};e.depthTexture.isArrayTexture&&(f.dimension=ft.TwoD,f.arrayLayerCount=1,f.baseArrayLayer=e.activeCubeFace),a.depthStencilView=p.texture.createView(f)}n[r]=a,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace,i.dimensions=s.dimensions}const l={colorAttachments:[]};for(let c=0;c<a.textureViews.length;c++){const h=a.textureViews[c];let u={r:0,g:0,b:0,a:1};c===0&&t.clearValue&&(u=t.clearValue),l.colorAttachments.push({view:h.view,depthSlice:h.depthSlice,resolveTarget:h.resolveTarget,loadOp:t.loadOp||Ce.Load,storeOp:t.storeOp||Ct.Store,clearValue:u})}return a.depthStencilView&&(l.depthStencilAttachment={view:a.depthStencilView}),l}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,n=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=n,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);let r;e.textures===null?r=this._getDefaultRenderPassDescriptor():r=this._getRenderPassDescriptor(e,{loadOp:Ce.Load}),this.initTimestampQuery(e,r),r.occlusionQuerySet=n;const a=r.depthStencilAttachment;if(e.textures!==null){const c=r.colorAttachments;for(let h=0;h<c.length;h++){const u=c[h];e.clearColor?(u.clearValue=h===0?e.clearColorValue:{r:0,g:0,b:0,a:1},u.loadOp=Ce.Clear):u.loadOp=Ce.Load,u.storeOp=Ct.Store}}else{const c=r.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=Ce.Clear):c.loadOp=Ce.Load,c.storeOp=Ct.Store}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=Ce.Clear):a.depthLoadOp=Ce.Load,a.depthStoreOp=Ct.Store),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=Ce.Clear):a.stencilLoadOp=Ce.Load,a.stencilStoreOp=Ct.Store);const l=s.createCommandEncoder({label:"renderContext_"+e.id});if(this._isRenderCameraDepthArray(e)===!0){const c=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==c.length?this._createDepthLayerDescriptors(e,t,r,c):this._updateDepthLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let h=0;h<c.length;h++){const u=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+h),d={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(u),t.bundleSets.push(d)}t.currentPass=null}else{const c=l.beginRenderPass(r);if(t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor){const{x:h,y:u,width:d,height:p}=e.scissorValue;c.setScissorRect(h,u,d,p)}}t.descriptor=r,t.encoder=l,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const n=s.depthStencilAttachment;t.layerDescriptors=[];const r=this.get(e.depthTexture);r.viewCache||(r.viewCache=[]);for(let a=0;a<i.length;a++){const l={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[a].view}]};if(s.depthStencilAttachment){const c=a;r.viewCache[c]||(r.viewCache[c]=r.texture.createView({dimension:ft.TwoD,baseArrayLayer:a,arrayLayerCount:1})),l.depthStencilAttachment={view:r.viewCache[c],depthLoadOp:n.depthLoadOp||Ce.Clear,depthStoreOp:n.depthStoreOp||Ct.Store,depthClearValue:n.depthClearValue||1},e.stencil&&(l.depthStencilAttachment.stencilLoadOp=n.stencilLoadOp,l.depthStencilAttachment.stencilStoreOp=n.stencilStoreOp,l.depthStencilAttachment.stencilClearValue=n.stencilClearValue)}else l.depthStencilAttachment={...n};t.layerDescriptors.push(l)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const n=t.layerDescriptors[i];if(n.depthStencilAttachment){const r=n.depthStencilAttachment;e.depth&&(e.clearDepth?(r.depthClearValue=e.clearDepthValue,r.depthLoadOp=Ce.Clear):r.depthLoadOp=Ce.Load),e.stencil&&(e.clearStencil?(r.stencilClearValue=e.clearStencilValue,r.stencilLoadOp=Ce.Clear):r.stencilLoadOp=Ce.Load)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const n=[];for(let r=0;r<t.bundleEncoders.length;r++){const a=t.bundleEncoders[r];n.push(a.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<n.length){const a=t.layerDescriptors[r],l=i.beginRenderPass(a);if(e.viewport){const{x:c,y:h,width:u,height:d,minDepth:p,maxDepth:f}=e.viewportValue;l.setViewport(c,h,u,d,p,f)}if(e.scissor){const{x:c,y:h,width:u,height:d}=e.scissorValue;l.setScissorRect(c,h,u,d)}l.executeBundles([n[r]]),l.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const n=s*8;let r=this.occludedResolveCache.get(n);r===void 0&&(r=this.device.createBuffer({size:n,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(n,r));const a=this.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,a,0,n),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const n=e.textures;for(let r=0;r<n.length;r++){const a=n[r];a.generateMipmaps===!0&&this.textureUtils.generateMipmaps(a)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const n=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),a=new BigUint64Array(r);for(let l=0;l<i.length;l++)a[l]===BigInt(0)&&n.add(i[l]);s.destroy(),t.occluded=n}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:n,height:r,minDepth:a,maxDepth:l}=e.viewportValue;t.setViewport(s,i,n,r,a,l)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const n=this.device,r=this.renderer;let a=[],l,c,h,u;if(e){const f=this.getClearColor();c={r:f.r,g:f.g,b:f.b,a:f.a}}if(i===null){h=r.depth,u=r.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const m=a[0];m.clearValue=c,m.loadOp=Ce.Clear,m.storeOp=Ct.Store}(h||u)&&(l=f.depthStencilAttachment)}else{h=i.depth,u=i.stencil;const f={loadOp:e?Ce.Clear:Ce.Load,clearValue:e?c:void 0};h&&(f.depthLoadOp=t?Ce.Clear:Ce.Load,f.depthClearValue=t?r.getClearDepth():void 0,f.depthStoreOp=Ct.Store),u&&(f.stencilLoadOp=s?Ce.Clear:Ce.Load,f.stencilClearValue=s?r.getClearStencil():void 0,f.stencilStoreOp=Ct.Store);const m=this._getRenderPassDescriptor(i,f);a=m.colorAttachments,l=m.depthStencilAttachment}h&&l&&l.depthLoadOp===void 0&&(t?(l.depthLoadOp=Ce.Clear,l.depthClearValue=r.getClearDepth(),l.depthStoreOp=Ct.Store):(l.depthLoadOp=Ce.Load,l.depthStoreOp=Ct.Store)),u&&l&&l.stencilLoadOp===void 0&&(s?(l.stencilLoadOp=Ce.Clear,l.stencilClearValue=r.getClearStencil(),l.stencilStoreOp=Ct.Store):(l.stencilLoadOp=Ce.Load,l.stencilStoreOp=Ct.Store));const d=n.createCommandEncoder({label:"clear"});d.beginRenderPass({colorAttachments:a,depthStencilAttachment:l}).end(),n.queue.submit([d.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i){const{passEncoderGPU:n}=this.get(e),r=this.get(i).pipeline;this.pipelineUtils.setPipeline(n,r);for(let h=0,u=s.length;h<u;h++){const d=s[h],p=this.get(d);n.setBindGroup(h,p.group)}const a=this.device.limits.maxComputeWorkgroupsPerDimension,l=this.get(t);l.dispatchSize===void 0&&(l.dispatchSize={x:0,y:1,z:1});const{dispatchSize:c}=l;t.dispatchCount>a?(c.x=Math.min(t.dispatchCount,a),c.y=Math.ceil(t.dispatchCount/a)):c.x=t.dispatchCount,n.dispatchWorkgroups(c.x,c.y,c.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,material:i,context:n,pipeline:r}=e,a=e.getBindings(),l=this.get(n),c=this.get(r).pipeline,h=e.getIndex(),u=h!==null,d=e.getDrawParameters();if(d===null)return;const p=(m,x)=>{this.pipelineUtils.setPipeline(m,c),x.pipeline=c;const g=x.bindingGroups;for(let b=0,T=a.length;b<T;b++){const S=a[b],C=this.get(S);g[S.index]!==S.id&&(m.setBindGroup(S.index,C.group),g[S.index]=S.id)}if(u===!0&&x.index!==h){const b=this.get(h).buffer,T=h.array instanceof Uint16Array?yr.Uint16:yr.Uint32;m.setIndexBuffer(b,T),x.index=h}const _=e.getVertexBuffers();for(let b=0,T=_.length;b<T;b++){const S=_[b];if(x.attributes[b]!==S){const C=this.get(S).buffer;m.setVertexBuffer(b,C),x.attributes[b]=S}}n.stencil===!0&&i.stencilWrite===!0&&l.currentStencilRef!==i.stencilRef&&(m.setStencilReference(i.stencilRef),l.currentStencilRef=i.stencilRef)},f=(m,x)=>{if(p(m,x),s.isBatchedMesh===!0){const g=s._multiDrawStarts,_=s._multiDrawCounts,b=s._multiDrawCount,T=s._multiDrawInstances;T!==null&&oi("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let S=0;S<b;S++){const C=T?T[S]:1,w=C>1?0:S;u===!0?m.drawIndexed(_[S],C,g[S]/h.array.BYTES_PER_ELEMENT,0,w):m.draw(_[S],C,g[S],w),t.update(s,_[S],C)}}else if(u===!0){const{vertexCount:g,instanceCount:_,firstVertex:b}=d,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer;m.drawIndexedIndirect(S,0)}else m.drawIndexed(g,_,b,0,0);t.update(s,g,_)}else{const{vertexCount:g,instanceCount:_,firstVertex:b}=d,T=e.getIndirect();if(T!==null){const S=this.get(T).buffer;m.drawIndirect(S,0)}else m.draw(g,_,b,0);t.update(s,g,_)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const m=this.get(e.camera),x=e.camera.cameras,g=e.getBindingGroup("cameraIndex");if(m.indexesGPU===void 0||m.indexesGPU.length!==x.length){const b=this.get(g),T=[],S=new Uint32Array([0,0,0,0]);for(let C=0,w=x.length;C<w;C++){S[0]=C;const R=this.bindingUtils.createBindGroupIndex(S,b.layout);T.push(R)}m.indexesGPU=T}const _=this.renderer.getPixelRatio();for(let b=0,T=x.length;b<T;b++){const S=x[b];if(s.layers.test(S.layers)){const C=S.viewport;let w=l.currentPass,R=l.currentSets;if(l.bundleEncoders){const P=l.bundleEncoders[b],z=l.bundleSets[b];w=P,R=z}C&&w.setViewport(Math.floor(C.x*_),Math.floor(C.y*_),Math.floor(C.width*_),Math.floor(C.height*_),n.viewportValue.minDepth,n.viewportValue.maxDepth),g&&m.indexesGPU&&(w.setBindGroup(g.index,m.indexesGPU[b]),R.bindingGroups[g.index]=g.id),f(w,R)}}}else if(l.currentPass){if(l.occlusionQuerySet!==void 0){const m=l.lastOcclusionObject;m!==s&&(m!==null&&m.occlusionTest===!0&&(l.currentPass.endOcclusionQuery(),l.occlusionQueryIndex++),s.occlusionTest===!0&&(l.currentPass.beginOcclusionQuery(l.occlusionQueryIndex),l.occlusionQueryObjects[l.occlusionQueryIndex]=s),l.lastOcclusionObject=s)}f(l.currentPass,l.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,n=this.utils,r=n.getSampleCountRenderContext(e.context),a=n.getCurrentColorSpace(e.context),l=n.getCurrentColorFormat(e.context),c=n.getCurrentDepthStencilFormat(e.context),h=n.getPrimitiveTopology(s,i);let u=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==r||t.colorSpace!==a||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==h||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=r,t.colorSpace=a,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=h,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,n=e.context;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,i.getSampleCountRenderContext(n),i.getCurrentColorSpace(n),i.getCurrentColorFormat(n),i.getCurrentDepthStencilFormat(n),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,n,r){return this.textureUtils.copyTextureToBuffer(e,t,s,i,n,r)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=e.isComputeNode?"compute":"render";this.timestampQueryPool[s]||(this.timestampQueryPool[s]=new mR(this.device,s,2048));const i=this.timestampQueryPool[s],n=i.allocateQueriesForContext(e);t.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:n,endOfPassWriteIndex:n+1}}createNodeBuilder(e,t){return new aR(e,t)}createProgram(e){const t=this.get(e);t.module={module:this.device.createShaderModule({code:e.code,label:e.stage+(e.name!==""?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),n=s.currentPass.finish();this.get(t).bundleGPU=n,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,n=0,r=0){let a=0,l=0,c=0,h=0,u=0,d=0,p=e.image.width,f=e.image.height,m=1;s!==null&&(s.isBox3===!0?(h=s.min.x,u=s.min.y,d=s.min.z,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=s.max.z-s.min.z):(h=s.min.x,u=s.min.y,p=s.max.x-s.min.x,f=s.max.y-s.min.y,m=1)),i!==null&&(a=i.x,l=i.y,c=i.z||0);const x=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;x.copyTextureToTexture({texture:g,mipLevel:n,origin:{x:h,y:u,z:d}},{texture:_,mipLevel:r,origin:{x:a,y:l,z:c}},[p,f,m]),this.device.queue.submit([x.finish()]),r===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let n=null;t.renderTarget?e.isDepthTexture?n=this.get(t.depthTexture).texture:n=this.get(t.textures[0]).texture:e.isDepthTexture?n=this.textureUtils.getDepthBuffer(t.depth,t.stencil):n=this.context.getCurrentTexture();const r=this.get(e).texture;if(n.format!==r.format){console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",n.format,r.format);return}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:n,origin:[s.x,s.y,0]},{texture:r},[s.z,s.w]),i.currentPass){const{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=Ce.Load;if(t.depth&&(l.depthStencilAttachment.depthLoadOp=Ce.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=Ce.Load),i.currentPass=a.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:c,y:h,width:u,height:d}=t.scissorValue;i.currentPass.setScissorRect(c,h,u,d)}}else this.device.queue.submit([a.finish()]);e.generateMipmaps&&this.textureUtils.generateMipmaps(e)}}class yR extends Vt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ve(16777215),this.specular=new ve(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.combine=pl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.flatShading=e.flatShading,this.fog=e.fog,this}}const xR=new yR;class _R extends it{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(xR),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ju(t):null}setupLightingModel(){return new Ry}setupVariants(){const e=(this.shininessNode?B(this.shininessNode):pw).max(1e-4);kh.assign(e);const t=this.specularNode||mw;Yt.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}class Vy extends Vt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new ve(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}const bR=new Vy;class Hy extends it{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(bR),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new OE(t):null}setupLightingModel(){return new Py}setupSpecular(){const e=Ge(I(.04),Se.rgb,rl);Yt.assign(e),al.assign(1)}setupVariants(){const e=this.metalnessNode?B(this.metalnessNode):xw;rl.assign(e);let t=this.roughnessNode?B(this.roughnessNode):yw;t=_y({roughness:t}),Xs.assign(t),this.setupSpecular(),Se.assign(ne(Se.rgb.mul(e.oneMinus()),Se.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}class TR extends Vy{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new he(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return pe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ve(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new ve(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ve(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}const SR=new TR;class vR extends Hy{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(SR),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){const e=this.iorNode?B(this.iorNode):Fw;Ba.assign(e),Yt.assign(Ge(fr(Ag(Ba.sub(1).div(Ba.add(1))).mul(gw),I(1)).mul(bp),Se.rgb,rl)),al.assign(Ge(bp,1,rl))}setupLightingModel(){return new Py(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?B(this.clearcoatNode):bw,s=this.clearcoatRoughnessNode?B(this.clearcoatRoughnessNode):Tw;Lh.assign(t),ol.assign(_y({roughness:s}))}if(this.useSheen){const t=this.sheenNode?I(this.sheenNode):ww,s=this.sheenRoughnessNode?B(this.sheenRoughnessNode):Mw;Xn.assign(t),Su.assign(s)}if(this.useIridescence){const t=this.iridescenceNode?B(this.iridescenceNode):Ew,s=this.iridescenceIORNode?B(this.iridescenceIORNode):Aw,i=this.iridescenceThicknessNode?B(this.iridescenceThicknessNode):Rw;vu.assign(t),pg.assign(s),fg.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?H(this.anisotropyNode):Cw).toVar();tn.assign(t.length()),Ze(tn.equal(0),()=>{t.assign(H(1,0))}).Else(()=>{t.divAssign(H(tn)),tn.assign(tn.saturate())}),Uh.assign(tn.pow2().mix(Xs.pow2(),1)),Oa.assign(so[0].mul(t.x).add(so[1].mul(t.y))),rr.assign(so[1].mul(t.x).sub(so[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?B(this.transmissionNode):Nw,s=this.thicknessNode?B(this.thicknessNode):Pw,i=this.attenuationDistanceNode?B(this.attenuationDistanceNode):Dw,n=this.attenuationColorNode?I(this.attenuationColorNode):Ow;if(zh.assign(t),mg.assign(s),gg.assign(i),yg.assign(n),this.useDispersion){const r=this.dispersionNode?B(this.dispersionNode):zw;xg.assign(r)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?I(this.clearcoatNormalNode):Sw}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const wR=L(({normal:o,lightDirection:e,builder:t})=>{const s=o.dot(e),i=H(s.mul(.5).add(.5),0);if(t.material.gradientMap){const n=Ei("gradientMap","texture").context({getUV:()=>i});return I(n.r)}else{const n=i.fwidth().mul(.5);return Ge(I(.7),I(1),Bi(B(.7).sub(n.x),B(.7).add(n.x),i.x))}});class MR extends Nl{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const n=wR({normal:Hg,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(n.mul(gr({diffuseColor:Se.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(gr({diffuseColor:Se}))),i.indirectDiffuse.mulAssign(t)}}class CR extends Vt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ve(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ER=new CR;class AR extends it{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ER),this.setValues(e)}setupLightingModel(){return new MR}}class RR extends Tr{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=B(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}const NR=new Ai;class PR extends it{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(NR),this.setValues(e)}setupNormal(){return zs}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ju(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new RR(iy)),t}setupOutgoingLight(){return Se.rgb}setupLightingModel(){return new Ay}}class FR extends Vt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ve(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new us,this.combine=pl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,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.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,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.flatShading=e.flatShading,this.fog=e.fog,this}}const DR=new FR;class OR extends it{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(DR),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new ju(t):null}setupLightingModel(){return new Ry(!1)}}class BR extends Vt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const IR=new BR;class LR extends it{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(IR),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?B(this.opacityNode):sy;Se.assign(Nu(ne(Dv(et),e),Xt))}}class UR extends Vt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ve(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Di,this.normalScale=new he(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}const kR=new UR;class zR extends it{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(kR),this.setValues(e)}setupVariants(e){const t=Nv;let s;e.material.matcap?s=Ei("matcap","texture").context({getUV:()=>t}):s=I(Ge(.2,.8,t.y)),Se.rgb.mulAssign(s.rgb)}}class Wy extends Vt{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ve(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}}const GR=new Wy;class VR extends it{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(GR),this.setValues(e)}}class HR extends Wy{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const WR=new HR;class $R extends it{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(WR),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?B(this.offsetNode):Uw,t=this.dashScaleNode?B(this.dashScaleNode):Bw,s=this.dashSizeNode?B(this.dashSizeNode):Iw,i=this.gapSizeNode?B(this.gapSizeNode):Lw;Jl.assign(s),cp.assign(i);const n=ws(Ii("lineDistance").mul(t));(e?n.add(e):n).mod(Jl.add(cp)).greaterThan(Jl).discard()}}class jR extends Vt{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ve(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!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.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const qR=new jR;class $y extends it{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(qR),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:n,rotationNode:r,scaleNode:a}=this,l=Sl.mul(I(n||0));let c=H(dn[0].xyz.length(),dn[1].xyz.length());if(a!==null&&(c=c.mul(H(a))),i===!1)if(s.isPerspectiveCamera)c=c.mul(l.z.negate());else{const p=B(2).div(Ou.element(1).element(1));c=c.mul(p.mul(2))}let h=vl.xy;if(t.center&&t.center.isVector2===!0){const p=HS("center","vec2",t);h=h.sub(p.sub(.5))}h=h.mul(c);const u=B(r||vw),d=$g(h,u);return ne(l.xy.add(d),l.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}class YR extends Vt{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new ve(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}}const XR=new YR;class ZR extends $y{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(XR),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Sl.mul(I(e||bt)).xyz}setupVertex(e){const t=super.setupVertex(e);if(e.material.isNodeMaterial!==!0)return t;const{rotationNode:s,scaleNode:i,sizeNode:n}=this,r=vl.xy.toVar(),a=po.z.div(po.w);if(s&&s.isNode){const c=B(s);r.assign($g(r,c))}let l=n!==null?H(n):kw;return this.sizeAttenuation===!0&&(l=l.mul(l.div(st.z.negate()))),i&&i.isNode&&(l=l.mul(H(i))),r.mulAssign(l.mul(2)),r.assign(r.div(po.z)),r.y.assign(r.y.mul(a)),r.assign(r.mul(t.w)),t.addAssign(ne(r,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class KR extends Nl{constructor(){super(),this.shadowNode=B(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Se.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Se.rgb)}}class QR extends Vt{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new ve(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}const JR=new QR;class eN extends it{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(JR),this.setValues(e)}setupLightingModel(){return new KR}}class gn extends dt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new ve(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}const Zc=new Ie,Of=new N,Bf=new N;class Ju{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new he(512,512),this.mapType=Nt,this.map=null,this.mapPass=null,this.matrix=new Ie,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Zu,this._frameExtents=new he(1,1),this._viewportCount=1,this._viewports=[new ge(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Of.setFromMatrixPosition(e.matrixWorld),t.position.copy(Of),Bf.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Bf),t.updateMatrixWorld(),Zc.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Zc),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Zc)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const If=new Ie,Wr=new N,Kc=new N;class tN extends Ju{constructor(){super(new Zt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new he(4,2),this._viewportCount=6,this._viewports=[new ge(2,1,1,1),new ge(0,1,1,1),new ge(3,1,1,1),new ge(1,1,1,1),new ge(3,0,1,1),new ge(1,0,1,1)],this._cubeDirections=[new N(1,0,0),new N(-1,0,0),new N(0,0,1),new N(0,0,-1),new N(0,1,0),new N(0,-1,0)],this._cubeUps=[new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,1,0),new N(0,0,1),new N(0,0,-1)]}updateMatrices(e,t=0){const s=this.camera,i=this.matrix,n=e.distance||s.far;n!==s.far&&(s.far=n,s.updateProjectionMatrix()),Wr.setFromMatrixPosition(e.matrixWorld),s.position.copy(Wr),Kc.copy(s.position),Kc.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(Kc),s.updateMatrixWorld(),i.makeTranslation(-Wr.x,-Wr.y,-Wr.z),If.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(If)}}class sN extends gn{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new tN}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class iN extends Ju{constructor(){super(new ku(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class nN extends gn{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.target=new dt,this.shadow=new iN}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class rN extends gn{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class oN extends Ju{constructor(){super(new Zt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=cr*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,n=e.distance||t.far;(s!==t.fov||i!==t.aspect||n!==t.far)&&(t.fov=s,t.aspect=i,t.far=n,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class ed extends gn{constructor(e,t,s=0,i=Math.PI/3,n=0,r=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.target=new dt,this.distance=s,this.angle=i,this.penumbra=n,this.decay=r,this.map=null,this.shadow=new oN}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class aN extends gn{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class lN extends gn{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(dt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ve(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}class cN{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new N)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,n=e.z,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.282095),t.addScaledVector(r[1],.488603*i),t.addScaledVector(r[2],.488603*n),t.addScaledVector(r[3],.488603*s),t.addScaledVector(r[4],1.092548*(s*i)),t.addScaledVector(r[5],1.092548*(i*n)),t.addScaledVector(r[6],.315392*(3*n*n-1)),t.addScaledVector(r[7],1.092548*(s*n)),t.addScaledVector(r[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,n=e.z,r=this.coefficients;return t.copy(r[0]).multiplyScalar(.886227),t.addScaledVector(r[1],2*.511664*i),t.addScaledVector(r[2],2*.511664*n),t.addScaledVector(r[3],2*.511664*s),t.addScaledVector(r[4],2*.429043*s*i),t.addScaledVector(r[5],2*.429043*i*n),t.addScaledVector(r[6],.743125*n*n-.247708),t.addScaledVector(r[7],2*.429043*s*n),t.addScaledVector(r[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){const s=e.x,i=e.y,n=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*n,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*n,t[6]=.315392*(3*n*n-1),t[7]=1.092548*s*n,t[8]=.546274*(s*s-i*i)}}class hN extends gn{constructor(e=new cN,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class uN extends ed{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class dN extends ed{constructor(e,t,s,i,n,r){super(e,t,s,i,n,r),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class pN extends Fy{constructor(){super(),this.addMaterial(_R,"MeshPhongMaterial"),this.addMaterial(Hy,"MeshStandardMaterial"),this.addMaterial(vR,"MeshPhysicalMaterial"),this.addMaterial(AR,"MeshToonMaterial"),this.addMaterial(PR,"MeshBasicMaterial"),this.addMaterial(OR,"MeshLambertMaterial"),this.addMaterial(LR,"MeshNormalMaterial"),this.addMaterial(zR,"MeshMatcapMaterial"),this.addMaterial(VR,"LineBasicMaterial"),this.addMaterial($R,"LineDashedMaterial"),this.addMaterial(ZR,"PointsMaterial"),this.addMaterial($y,"SpriteMaterial"),this.addMaterial(eN,"ShadowMaterial"),this.addLight(xC,sN),this.addLight(CE,nN),this.addLight(EE,rN),this.addLight($u,ed),this.addLight(PE,aN),this.addLight(FE,lN),this.addLight(DE,hN),this.addLight(AE,uN),this.addLight(NE,dN),this.addToneMapping(CM,F_),this.addToneMapping(EM,D_),this.addToneMapping(AM,O_),this.addToneMapping(NM,B_),this.addToneMapping(OM,I_),this.addToneMapping(BM,L_)}}class xa extends bA{constructor(e={}){let t;e.forceWebGL?t=Cf:(t=gR,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Cf(e)));const s=new t(e);super(s,e),this.library=new pN,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class fN extends y.Line{constructor(e,t){const s=[1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],i=new y.BufferGeometry;i.setAttribute("position",new y.Float32BufferAttribute(s,3)),i.computeBoundingSphere();const n=new y.LineBasicMaterial({fog:!1});super(i,n),this.light=e,this.color=t,this.type="RectAreaLightHelper";const r=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],a=new y.BufferGeometry;a.setAttribute("position",new y.Float32BufferAttribute(r,3)),a.computeBoundingSphere(),this.add(new y.Mesh(a,new y.MeshBasicMaterial({side:y.BackSide,fog:!1})))}updateMatrixWorld(){if(this.scale.set(.5*this.light.width,.5*this.light.height,1),this.color!==void 0)this.material.color.set(this.color),this.children[0].material.color.set(this.color);else{this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);const e=this.material.color,t=Math.max(e.r,e.g,e.b);t>1&&e.multiplyScalar(1/t),this.children[0].material.color.copy(this.material.color)}this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld),this.children[0].matrixWorld.copy(this.matrixWorld)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const Lf={type:"change"},td={type:"start"},jy={type:"end"},_a=new y.Ray,Uf=new y.Plane,mN=Math.cos(70*y.MathUtils.DEG2RAD),lt=new y.Vector3,It=2*Math.PI,Fe={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Qc=1e-6;class gN extends y.Controls{constructor(e,t=null){super(e,t),this.state=Fe.NONE,this.target=new y.Vector3,this.cursor=new y.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:y.MOUSE.ROTATE,MIDDLE:y.MOUSE.DOLLY,RIGHT:y.MOUSE.PAN},this.touches={ONE:y.TOUCH.ROTATE,TWO:y.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new y.Vector3,this._lastQuaternion=new y.Quaternion,this._lastTargetPosition=new y.Vector3,this._quat=new y.Quaternion().setFromUnitVectors(e.up,new y.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new y.Spherical,this._sphericalDelta=new y.Spherical,this._scale=1,this._panOffset=new y.Vector3,this._rotateStart=new y.Vector2,this._rotateEnd=new y.Vector2,this._rotateDelta=new y.Vector2,this._panStart=new y.Vector2,this._panEnd=new y.Vector2,this._panDelta=new y.Vector2,this._dollyStart=new y.Vector2,this._dollyEnd=new y.Vector2,this._dollyDelta=new y.Vector2,this._dollyDirection=new y.Vector3,this._mouse=new y.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=xN.bind(this),this._onPointerDown=yN.bind(this),this._onPointerUp=_N.bind(this),this._onContextMenu=CN.bind(this),this._onMouseWheel=SN.bind(this),this._onKeyDown=vN.bind(this),this._onTouchStart=wN.bind(this),this._onTouchMove=MN.bind(this),this._onMouseDown=bN.bind(this),this._onMouseMove=TN.bind(this),this._interceptControlDown=EN.bind(this),this._interceptControlUp=AN.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Lf),this.update(),this.state=Fe.NONE}update(e=null){const t=this.object.position;lt.copy(t).sub(this.target),lt.applyQuaternion(this._quat),this._spherical.setFromVector3(lt),this.autoRotate&&this.state===Fe.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let s=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(s)&&isFinite(i)&&(s<-Math.PI?s+=It:s>Math.PI&&(s-=It),i<-Math.PI?i+=It:i>Math.PI&&(i-=It),s<=i?this._spherical.theta=Math.max(s,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(s+i)/2?Math.max(s,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=r!=this._spherical.radius}if(lt.setFromSpherical(this._spherical),lt.applyQuaternion(this._quatInverse),t.copy(this.target).add(lt),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=lt.length();r=this._clampDistance(a*this._scale);const l=a-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),n=!!l}else if(this.object.isOrthographicCamera){const a=new y.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=l!==this.object.zoom;const c=new y.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),r=lt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(_a.origin.copy(this.object.position),_a.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(_a.direction))<mN?this.object.lookAt(this.target):(Uf.setFromNormalAndCoplanarPoint(this.object.up,this.target),_a.intersectPlane(Uf,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>Qc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Qc||this._lastTargetPosition.distanceToSquared(this.target)>Qc?(this.dispatchEvent(Lf),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?It/60*this.autoRotateSpeed*e:It/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){lt.setFromMatrixColumn(t,0),lt.multiplyScalar(-e),this._panOffset.add(lt)}_panUp(e,t){this.screenSpacePanning===!0?lt.setFromMatrixColumn(t,1):(lt.setFromMatrixColumn(t,0),lt.crossVectors(this.object.up,lt)),lt.multiplyScalar(e),this._panOffset.add(lt)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;lt.copy(i).sub(this.target);let n=lt.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*n/s.clientHeight,this.object.matrix),this._panUp(2*t*n/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,n=t-s.top,r=s.width,a=s.height;this._mouse.x=i/r*2-1,this._mouse.y=-(n/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(It*this._rotateDelta.x/t.clientHeight),this._rotateUp(It*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-It*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const s=this._getSecondPointerPosition(e),i=.5*(e.pageX+s.x),n=.5*(e.pageY+s.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(It*this._rotateDelta.x/t.clientHeight),this._rotateUp(It*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,n),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new y.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function yN(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function xN(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function _N(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(jy),this.state=Fe.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function bN(o){let e;switch(o.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case y.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=Fe.DOLLY;break;case y.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=Fe.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=Fe.ROTATE}break;case y.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=Fe.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=Fe.PAN}break;default:this.state=Fe.NONE}this.state!==Fe.NONE&&this.dispatchEvent(td)}function TN(o){switch(this.state){case Fe.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case Fe.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case Fe.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function SN(o){this.enabled===!1||this.enableZoom===!1||this.state!==Fe.NONE||(o.preventDefault(),this.dispatchEvent(td),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(jy))}function vN(o){this.enabled!==!1&&this._handleKeyDown(o)}function wN(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case y.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=Fe.TOUCH_ROTATE;break;case y.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=Fe.TOUCH_PAN;break;default:this.state=Fe.NONE}break;case 2:switch(this.touches.TWO){case y.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=Fe.TOUCH_DOLLY_PAN;break;case y.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=Fe.TOUCH_DOLLY_ROTATE;break;default:this.state=Fe.NONE}break;default:this.state=Fe.NONE}this.state!==Fe.NONE&&this.dispatchEvent(td)}function MN(o){switch(this._trackPointer(o),this.state){case Fe.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case Fe.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case Fe.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case Fe.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=Fe.NONE}}function CN(o){this.enabled!==!1&&o.preventDefault()}function EN(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function AN(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}/*!
|
|
481
481
|
* camera-controls
|
|
482
482
|
* https://github.com/yomotsu/camera-controls
|
|
483
483
|
* (c) 2017 @yomotsu
|
|
484
484
|
* Released under the MIT License.
|
|
485
|
-
*/const $e={LEFT:1,RIGHT:2,MIDDLE:4},F=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),zn={NONE:0,IN:1,OUT:-1};function Xi(o){return o.isPerspectiveCamera}function Ti(o){return o.isOrthographicCamera}const Vn=Math.PI*2,If=Math.PI/2,Hy=1e-5,Hr=Math.PI/180;function ys(o,e,t){return Math.max(e,Math.min(t,o))}function Le(o,e=Hy){return Math.abs(o)<e}function Ae(o,e,t=Hy){return Le(o-e,t)}function Lf(o,e){return Math.round(o/e)*e}function Wr(o){return isFinite(o)?o:o<0?-Number.MAX_VALUE:Number.MAX_VALUE}function $r(o){return Math.abs(o)<Number.MAX_VALUE?o:o*(1/0)}function _a(o,e,t,s,i=1/0,n){s=Math.max(1e-4,s);const r=2/s,a=r*n,l=1/(1+a+.48*a*a+.235*a*a*a);let c=o-e;const h=e,u=i*s;c=ys(c,-u,u),e=o-c;const d=(t.value+r*c)*n;t.value=(t.value-r*d)*l;let p=e+(c+d)*l;return h-o>0==p>h&&(p=h,t.value=(p-h)/n),p}function Uf(o,e,t,s,i=1/0,n,r){s=Math.max(1e-4,s);const a=2/s,l=a*n,c=1/(1+l+.48*l*l+.235*l*l*l);let h=e.x,u=e.y,d=e.z,p=o.x-h,f=o.y-u,m=o.z-d;const y=h,g=u,_=d,b=i*s,T=b*b,S=p*p+f*f+m*m;if(S>T){const Z=Math.sqrt(S);p=p/Z*b,f=f/Z*b,m=m/Z*b}h=o.x-p,u=o.y-f,d=o.z-m;const C=(t.x+a*p)*n,w=(t.y+a*f)*n,R=(t.z+a*m)*n;t.x=(t.x-a*C)*c,t.y=(t.y-a*w)*c,t.z=(t.z-a*R)*c,r.x=h+(p+C)*c,r.y=u+(f+w)*c,r.z=d+(m+R)*c;const P=y-o.x,z=g-o.y,$=_-o.z,q=r.x-y,j=r.y-g,X=r.z-_;return P*q+z*j+$*X>0&&(r.x=y,r.y=g,r.z=_,t.x=(r.x-y)/n,t.y=(r.y-g)/n,t.z=(r.z-_)/n),r}function Zc(o,e){e.set(0,0),o.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=o.length,e.y/=o.length}function Qc(o,e){return Ti(o)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class rN{constructor(){this._listeners={}}addEventListener(e,t){const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const s=this._listeners[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,r=i.length;n<r;n++)i[n].call(this,e)}}}var Kc;const oN="2.10.1",ba=1/8,aN=/Mac/.test((Kc=globalThis?.navigator)===null||Kc===void 0?void 0:Kc.platform);let J,kf,Ta,Jc,Lt,le,Te,Gn,jr,As,Rs,Zi,zf,Vf,ts,qr,Hn,Gf,eh,Hf,th,sh,Sa;class Ds extends rN{static install(e){J=e.THREE,kf=Object.freeze(new J.Vector3(0,0,0)),Ta=Object.freeze(new J.Vector3(0,1,0)),Jc=Object.freeze(new J.Vector3(0,0,1)),Lt=new J.Vector2,le=new J.Vector3,Te=new J.Vector3,Gn=new J.Vector3,jr=new J.Vector3,As=new J.Vector3,Rs=new J.Vector3,Zi=new J.Vector3,zf=new J.Vector3,Vf=new J.Vector3,ts=new J.Spherical,qr=new J.Spherical,Hn=new J.Box3,Gf=new J.Box3,eh=new J.Sphere,Hf=new J.Quaternion,th=new J.Quaternion,sh=new J.Matrix4,Sa=new J.Raycaster}static get ACTION(){return F}set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(e,t){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=F.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=zn.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new J.Vector3,this._focalOffsetVelocity=new J.Vector3,this._zoomVelocity={value:0},this._truckInternal=(g,_,b,T)=>{let S,C;if(Xi(this._camera)){const w=le.copy(this._camera.position).sub(this._target),R=this._camera.getEffectiveFOV()*Hr,P=w.length()*Math.tan(R*.5);S=this.truckSpeed*g*P/this._elementRect.height,C=this.truckSpeed*_*P/this._elementRect.height}else if(Ti(this._camera)){const w=this._camera;S=this.truckSpeed*g*(w.right-w.left)/w.zoom/this._elementRect.width,C=this.truckSpeed*_*(w.top-w.bottom)/w.zoom/this._elementRect.height}else return;T?(b?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-C,!0)):b?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+C,this._focalOffsetEnd.z,!0):this.truck(S,C,!0)},this._rotateInternal=(g,_)=>{const b=Vn*this.azimuthRotateSpeed*g/this._elementRect.height,T=Vn*this.polarRotateSpeed*_/this._elementRect.height;this.rotate(b,T,!0)},this._dollyInternal=(g,_,b)=>{const T=Math.pow(.95,-g*this.dollySpeed),S=this._sphericalEnd.radius,C=this._sphericalEnd.radius*T,w=ys(C,this.minDistance,this.maxDistance),R=w-C;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(C,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(R,!0),this._dollyToNoClamp(w,!0)):this._dollyToNoClamp(w,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?C:w)-S,this._dollyControlCoord.set(_,b)),this._lastDollyDirection=Math.sign(-g)},this._zoomInternal=(g,_,b)=>{const T=Math.pow(.95,g*this.dollySpeed),S=this._zoom,C=this._zoom*T;this.zoomTo(C,!0),this.dollyToCursor&&(this._changedZoom+=C-S,this._dollyControlCoord.set(_,b))},typeof J>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new J.Quaternion().setFromUnitVectors(this._camera.up,Ta),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=F.NONE,this._target=new J.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new J.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new J.Spherical().setFromVector3(le.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new J.Vector3,new J.Vector3,new J.Vector3,new J.Vector3],this._updateNearPlaneCorners(),this._boundary=new J.Box3(new J.Vector3(-1/0,-1/0,-1/0),new J.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new J.Vector2,this.mouseButtons={left:F.ROTATE,middle:F.DOLLY,right:F.TRUCK,wheel:Xi(this._camera)?F.DOLLY:Ti(this._camera)?F.ZOOM:F.NONE},this.touches={one:F.TOUCH_ROTATE,two:Xi(this._camera)?F.TOUCH_DOLLY_TRUCK:Ti(this._camera)?F.TOUCH_ZOOM_TRUCK:F.NONE,three:F.TOUCH_TRUCK};const s=new J.Vector2,i=new J.Vector2,n=new J.Vector2,r=g=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const T=this._domElement.getBoundingClientRect(),S=g.clientX/T.width,C=g.clientY/T.height;if(S<this._interactiveArea.left||S>this._interactiveArea.right||C<this._interactiveArea.top||C>this._interactiveArea.bottom)return}const _=g.pointerType!=="mouse"?null:(g.buttons&$e.LEFT)===$e.LEFT?$e.LEFT:(g.buttons&$e.MIDDLE)===$e.MIDDLE?$e.MIDDLE:(g.buttons&$e.RIGHT)===$e.RIGHT?$e.RIGHT:null;if(_!==null){const T=this._findPointerByMouseButton(_);T&&this._disposePointer(T)}if((g.buttons&$e.LEFT)===$e.LEFT&&this._lockedPointer)return;const b={pointerId:g.pointerId,clientX:g.clientX,clientY:g.clientY,deltaX:0,deltaY:0,mouseButton:_};this._activePointers.push(b),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,d(g)},a=g=>{g.cancelable&&g.preventDefault();const _=g.pointerId,b=this._lockedPointer||this._findPointerById(_);if(b){if(b.clientX=g.clientX,b.clientY=g.clientY,b.deltaX=g.movementX,b.deltaY=g.movementY,this._state=0,g.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(g.buttons&$e.LEFT)===$e.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(g.buttons&$e.MIDDLE)===$e.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(g.buttons&$e.RIGHT)===$e.RIGHT&&(this._state=this._state|this.mouseButtons.right);p()}},l=g=>{const _=this._findPointerById(g.pointerId);if(!(_&&_===this._lockedPointer)){if(_&&this._disposePointer(_),g.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=F.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=F.NONE;f()}};let c=-1;const h=g=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===F.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const C=this._domElement.getBoundingClientRect(),w=g.clientX/C.width,R=g.clientY/C.height;if(w<this._interactiveArea.left||w>this._interactiveArea.right||R<this._interactiveArea.top||R>this._interactiveArea.bottom)return}if(g.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===F.ROTATE||this.mouseButtons.wheel===F.TRUCK){const C=performance.now();c-C<1e3&&this._getClientRect(this._elementRect),c=C}const _=aN?-1:-3,b=g.deltaMode===1||g.ctrlKey?g.deltaY/_:g.deltaY/(_*10),T=this.dollyToCursor?(g.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(g.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case F.ROTATE:{this._rotateInternal(g.deltaX,g.deltaY),this._isUserControllingRotate=!0;break}case F.TRUCK:{this._truckInternal(g.deltaX,g.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case F.SCREEN_PAN:{this._truckInternal(g.deltaX,g.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case F.OFFSET:{this._truckInternal(g.deltaX,g.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case F.DOLLY:{this._dollyInternal(-b,T,S),this._isUserControllingDolly=!0;break}case F.ZOOM:{this._zoomInternal(-b,T,S),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=g=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Ds.ACTION.NONE){const _=g instanceof PointerEvent?g.pointerId:0,b=this._findPointerById(_);b&&this._disposePointer(b),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}g.preventDefault()}},d=g=>{if(!this._enabled)return;if(Zc(this._activePointers,Lt),this._getClientRect(this._elementRect),s.copy(Lt),i.copy(Lt),this._activePointers.length>=2){const b=Lt.x-this._activePointers[1].clientX,T=Lt.y-this._activePointers[1].clientY,S=Math.sqrt(b*b+T*T);n.set(0,S);const C=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,w=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(C,w)}if(this._state=0,!g)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in g&&g.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(g.buttons&$e.LEFT)===$e.LEFT&&(this._state=this._state|this.mouseButtons.left),(g.buttons&$e.MIDDLE)===$e.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(g.buttons&$e.RIGHT)===$e.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&F.ROTATE)===F.ROTATE||(this._state&F.TOUCH_ROTATE)===F.TOUCH_ROTATE||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&F.TRUCK)===F.TRUCK||(this._state&F.SCREEN_PAN)===F.SCREEN_PAN||(this._state&F.TOUCH_TRUCK)===F.TOUCH_TRUCK||(this._state&F.TOUCH_SCREEN_PAN)===F.TOUCH_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&F.DOLLY)===F.DOLLY||(this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&F.ZOOM)===F.ZOOM||(this._state&F.TOUCH_ZOOM)===F.TOUCH_ZOOM||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&F.OFFSET)===F.OFFSET||(this._state&F.TOUCH_OFFSET)===F.TOUCH_OFFSET||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Zc(this._activePointers,Lt);const _=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,b=_?-_.deltaX:i.x-Lt.x,T=_?-_.deltaY:i.y-Lt.y;if(i.copy(Lt),((this._state&F.ROTATE)===F.ROTATE||(this._state&F.TOUCH_ROTATE)===F.TOUCH_ROTATE||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(b,T),this._isUserControllingRotate=!0),(this._state&F.DOLLY)===F.DOLLY||(this._state&F.ZOOM)===F.ZOOM){const S=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,C=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,w=this.dollyDragInverted?-1:1;(this._state&F.DOLLY)===F.DOLLY?(this._dollyInternal(w*T*ba,S,C),this._isUserControllingDolly=!0):(this._zoomInternal(w*T*ba,S,C),this._isUserControllingZoom=!0)}if((this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_ZOOM)===F.TOUCH_ZOOM||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE){const S=Lt.x-this._activePointers[1].clientX,C=Lt.y-this._activePointers[1].clientY,w=Math.sqrt(S*S+C*C),R=n.y-w;n.set(0,w);const P=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,z=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET?(this._dollyInternal(R*ba,P,z),this._isUserControllingDolly=!0):(this._zoomInternal(R*ba,P,z),this._isUserControllingZoom=!0)}((this._state&F.TRUCK)===F.TRUCK||(this._state&F.TOUCH_TRUCK)===F.TOUCH_TRUCK||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(b,T,!1,!1),this._isUserControllingTruck=!0),((this._state&F.SCREEN_PAN)===F.SCREEN_PAN||(this._state&F.TOUCH_SCREEN_PAN)===F.TOUCH_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(b,T,!1,!0),this._isUserControllingTruck=!0),((this._state&F.OFFSET)===F.OFFSET||(this._state&F.TOUCH_OFFSET)===F.TOUCH_OFFSET||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(b,T,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{Zc(this._activePointers,Lt),i.copy(Lt),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",m),this._domElement.ownerDocument.addEventListener("pointerlockerror",y),this._domElement.ownerDocument.addEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var g,_,b;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(g=this._domElement)===null||g===void 0||g.ownerDocument.exitPointerLock(),(_=this._domElement)===null||_===void 0||_.ownerDocument.removeEventListener("pointerlockchange",m),(b=this._domElement)===null||b===void 0||b.ownerDocument.removeEventListener("pointerlockerror",y),this.cancel()};const m=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},y=()=>{this.unlockPointer()};this._addAllEventListeners=g=>{this._domElement=g,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",m),this._domElement.ownerDocument.removeEventListener("pointerlockerror",y))},this.cancel=()=>{this._state!==F.NONE&&(this._state=F.NONE,this._activePointers.length=0,f())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=ys(e.width,0,1),this._interactiveArea.height=ys(e.height,0,1),this._interactiveArea.x=ys(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=ys(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,s)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,s=!1){this._isUserControllingRotate=!1;const i=ys(e,this.minAzimuthAngle,this.maxAzimuthAngle),n=ys(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=i,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!s||Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=zn.NONE,this._changedDolly=0,this._dollyToNoClamp(ys(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),a=Ae(r,this._spherical.radius);if(!(s>e)&&a)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const n=!t||Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(jr).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(s)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=ys(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||Ae(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(s)}pan(e,t,s=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,s)}truck(e,t,s=!1){this._camera.updateMatrix(),As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),As.multiplyScalar(e),Rs.multiplyScalar(-t);const i=le.copy(As).add(Rs),n=Te.copy(this._targetEnd).add(i);return this.moveTo(n.x,n.y,n.z,s)}forward(e,t=!1){le.setFromMatrixColumn(this._camera.matrix,0),le.crossVectors(this._camera.up,le),le.multiplyScalar(e);const s=Te.copy(this._targetEnd).add(le);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return le.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+le.x,this._targetEnd.y+le.y,this._targetEnd.z+le.z,t)}moveTo(e,t,s,i=!1){this._isUserControllingTruck=!1;const n=le.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,i||this._target.copy(this._targetEnd);const r=!i||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,s,i=!1){const a=le.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(a.x,a.y,a.z,i)}fitToBox(e,t,{cover:s=!1,paddingLeft:i=0,paddingRight:n=0,paddingBottom:r=0,paddingTop:a=0}={}){const l=[],c=e.isBox3?Hn.copy(e):Hn.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=Lf(this._sphericalEnd.theta,If),u=Lf(this._sphericalEnd.phi,If);l.push(this.rotateTo(h,u,t));const d=le.setFromSpherical(this._sphericalEnd).normalize(),p=Hf.setFromUnitVectors(d,Jc),f=Ae(Math.abs(d.y),1);f&&p.multiply(th.setFromAxisAngle(Ta,h)),p.multiply(this._yAxisUpSpaceInverse);const m=Gf.makeEmpty();Te.copy(c.min).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setX(c.max.x).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setY(c.max.y).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setZ(c.min.z).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setZ(c.max.z).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setY(c.min.y).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setX(c.min.x).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).applyQuaternion(p),m.expandByPoint(Te),m.min.x-=i,m.min.y-=r,m.max.x+=n,m.max.y+=a,p.setFromUnitVectors(Jc,d),f&&p.premultiply(th.invert()),p.premultiply(this._yAxisUpSpace);const y=m.getSize(le),g=m.getCenter(Te).applyQuaternion(p);if(Xi(this._camera)){const _=this.getDistanceToFitBox(y.x,y.y,y.z,s);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.dollyTo(_,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Ti(this._camera)){const _=this._camera,b=_.right-_.left,T=_.top-_.bottom,S=s?Math.max(b/y.x,T/y.y):Math.min(b/y.x,T/y.y);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.zoomTo(S,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const s=[],n="isObject3D"in e?Ds.createBoundingSphere(e,eh):eh.copy(e);if(s.push(this.moveTo(n.center.x,n.center.y,n.center.z,t)),Xi(this._camera)){const r=this.getDistanceToFitSphere(n.radius);s.push(this.dollyTo(r,t))}else if(Ti(this._camera)){const r=this._camera.right-this._camera.left,a=this._camera.top-this._camera.bottom,l=2*n.radius,c=Math.min(r/l,a/l);s.push(this.zoomTo(c,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,i,n,r,a=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=zn.NONE,this._changedDolly=0;const l=Te.set(i,n,r),c=le.set(e,t,s);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,a||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!a||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold)&&Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(e,t,s,i,n,r,a,l,c,h,u,d,p,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=zn.NONE,this._changedDolly=0;const m=le.set(i,n,r),y=Te.set(e,t,s);ts.setFromVector3(y.sub(m).applyQuaternion(this._yAxisUpSpace));const g=Gn.set(h,u,d),_=Te.set(a,l,c);qr.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(m.lerp(g,p));const b=qr.theta-ts.theta,T=qr.phi-ts.phi,S=qr.radius-ts.radius;this._sphericalEnd.set(ts.radius+S*p,ts.phi+T*p,ts.theta+b*p),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const C=!f||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold)&&Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(C)}setPosition(e,t,s,i=!1){return this.setLookAt(e,t,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,i)}setTarget(e,t,s,i=!1){const n=this.getPosition(le),r=this.setLookAt(n.x,n.y,n.z,e,t,s,i);return this._sphericalEnd.phi=ys(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,s,i=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,s),this._needsUpdate=!0,i||this._focalOffset.copy(this._focalOffsetEnd);const n=!i||Ae(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ae(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ae(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),As.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Rs.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Zi.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const i=le.set(e,t,s),n=i.distanceTo(this._camera.position),r=i.sub(this._camera.position);As.multiplyScalar(r.x),Rs.multiplyScalar(r.y),Zi.multiplyScalar(r.z),le.copy(As).add(Rs).add(Zi),le.z=le.z+n,this.dollyTo(n,!1),this.setFocalOffset(-le.x,le.y,-le.z,!1),this.moveTo(e,t,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,s,i){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new J.Vector4,typeof e=="number"?this._viewport.set(e,t,s,i):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,i=!1){if(Qc(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=e/t,r=this._camera.getEffectiveFOV()*Hr,a=this._camera.aspect;return((i?n>a:n<a)?t:e/a)*.5/Math.tan(r*.5)+s*.5}getDistanceToFitSphere(e){if(Qc(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*Hr,s=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,i=1<this._camera.aspect?t:s;return e/Math.sin(i*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new J.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Vn,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Vn),this._spherical.theta+=Vn*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Vn)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Ae(this._camera.up.x,this._cameraUp0.x)||!Ae(this._camera.up.y,this._cameraUp0.y)||!Ae(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(le);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}const t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Ta),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=le.subVectors(this._target,this._camera.position).normalize(),t=Te.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(le);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}update(e){const t=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,i=this._sphericalEnd.radius-this._spherical.radius,n=zf.subVectors(this._targetEnd,this._target),r=Vf.subVectors(this._focalOffsetEnd,this._focalOffset),a=this._zoomEnd-this._zoom;if(Le(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=_a(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,e),this._needsUpdate=!0}if(Le(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=_a(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,e),this._needsUpdate=!0}if(Le(i))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=_a(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,e),this._needsUpdate=!0}if(Le(n.x)&&Le(n.y)&&Le(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Uf(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(Le(r.x)&&Le(r.y)&&Le(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Uf(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(Le(a))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=_a(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,e)}if(this.dollyToCursor){if(Xi(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,d=this._camera,p=this._getCameraDirection(jr),f=le.copy(p).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const m=Te.crossVectors(f,p),y=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*Hr*.5),_=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,b=Gn.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*y*d.aspect)).add(m.multiplyScalar(this._dollyControlCoord.y*y)),T=le.copy(this._targetEnd).lerp(b,_),S=this._lastDollyDirection===zn.IN&&this._spherical.radius<=this.minDistance,C=this._lastDollyDirection===zn.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(S||C)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const R=Te.copy(p).multiplyScalar(-u);T.add(R)}this._boundary.clampPoint(T,T);const w=Te.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(w),this._changedDolly-=u,Le(this._changedDolly)&&(this._changedDolly=0)}else if(Ti(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,d=this._camera,p=le.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),f=Te.set(0,0,-1).applyQuaternion(d.quaternion),m=Gn.copy(p).add(f.multiplyScalar(-p.dot(d.up))),g=-(this._zoom-u-this._zoom)/this._zoom,_=this._getCameraDirection(jr),b=this._targetEnd.dot(_),T=le.copy(this._targetEnd).lerp(m,g),S=T.dot(_),C=_.multiplyScalar(S-b);T.sub(C),this._boundary.clampPoint(T,T);const w=Te.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(w),this._changedZoom-=u,Le(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const l=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,l),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!Le(this._focalOffset.x)||!Le(this._focalOffset.y)||!Le(this._focalOffset.z))&&(As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),Zi.setFromMatrixColumn(this._camera.matrix,2),As.multiplyScalar(this._focalOffset.x),Rs.multiplyScalar(-this._focalOffset.y),Zi.multiplyScalar(this._focalOffset.z),le.copy(As).add(Rs).add(Zi),this._camera.position.add(le),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),le.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const h=this._needsUpdate;return h&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):h?(this.dispatchEvent({type:"update"}),Le(t,this.restThreshold)&&Le(s,this.restThreshold)&&Le(i,this.restThreshold)&&Le(n.x,this.restThreshold)&&Le(n.y,this.restThreshold)&&Le(n.z,this.restThreshold)&&Le(r.x,this.restThreshold)&&Le(r.y,this.restThreshold)&&Le(r.z,this.restThreshold)&&Le(a,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!h&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=h,this._needsUpdate=!1,h}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:Wr(this.maxDistance),minZoom:this.minZoom,maxZoom:Wr(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:Wr(this.maxPolarAngle),minAzimuthAngle:Wr(this.minAzimuthAngle),maxAzimuthAngle:Wr(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:le.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){const s=JSON.parse(e);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=$r(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=$r(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=$r(s.maxPolarAngle),this.minAzimuthAngle=$r(s.minAzimuthAngle),this.maxAzimuthAngle=$r(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],t),ts.setFromVector3(le.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ts.theta,ts.phi,t),this.dollyTo(ts.radius,t),this.zoomTo(s.zoom,t),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}e.setAttribute("data-camera-controls-version",oN),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,s){const i=t.lengthSq();if(i===0)return e;const n=Te.copy(t).add(e),a=this._boundary.clampPoint(n,Gn).sub(n),l=a.lengthSq();if(l===0)return e.add(t);if(l===i)return e;if(s===0)return e.add(t).add(a);{const c=1+s*l/t.dot(a);return e.add(Te.copy(t).multiplyScalar(c)).add(a.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(Xi(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*Hr,i=Math.tan(s*.5)*t,n=i*e.aspect;this._nearPlaneCorners[0].set(-n,-i,0),this._nearPlaneCorners[1].set(n,-i,0),this._nearPlaneCorners[2].set(n,i,0),this._nearPlaneCorners[3].set(-n,i,0)}else if(Ti(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,i=e.right*t,n=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(s,n,0),this._nearPlaneCorners[1].set(i,n,0),this._nearPlaneCorners[2].set(i,r,0),this._nearPlaneCorners[3].set(s,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Qc(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(jr);sh.lookAt(kf,s,this._camera.up);for(let i=0;i<4;i++){const n=Te.copy(this._nearPlaneCorners[i]);n.applyMatrix4(sh);const r=Gn.addVectors(this._target,n);Sa.set(r,s),Sa.far=this._spherical.radius+1;const a=Sa.intersectObjects(this.colliderMeshes);a.length!==0&&a[0].distance<e&&(e=a[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const s=()=>{this.removeEventListener("rest",s),t()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new J.Sphere){const s=t,i=s.center;Hn.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&Hn.expandByObject(r)}),Hn.getCenter(i);let n=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const a=r;if(!a.geometry)return;const l=a.geometry.clone();l.applyMatrix4(a.matrixWorld);const h=l.attributes.position;for(let u=0,d=h.count;u<d;u++)le.fromBufferAttribute(h,u),n=Math.max(n,i.distanceToSquared(le))}),s.radius=Math.sqrt(n),s}}const ll=o=>{const[e,t]=W.useState(o.options[o.index]),s=()=>{o.onToggle(!o.open)},i=r=>{r!==e&&(o.onSelect(r),t(r)),o.onToggle(!1)},n=o.open?`${o.options.length*31-1}px`:"0px";return E.jsxs("div",{className:`dropdown ${o.up===!0?"up":""}`,children:[E.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${o.title}: ${e}`}),E.jsx("ul",{className:"dropdown-menu",style:{height:n},children:o.options.map(r=>E.jsx("li",{onClick:()=>i(r),children:r},r))})]})},Qi=W.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[i,n]=W.useState("Renderer"),[r,a]=W.useState(!1),[l,c]=W.useState(!1),[h,u]=W.useState(!1);return E.jsxs("div",{className:`CameraWindow ${e.name}`,children:[E.jsx("div",{ref:t,className:"clickable",onClick:()=>{h&&u(!1)}}),E.jsxs("div",{className:"options",children:[e.camera!==null&&E.jsx(ll,{title:"Camera",index:e.options.indexOf(e.camera.name),open:h,options:e.options,onSelect:e.onSelectCamera,onToggle:d=>{d&&l&&c(!1),u(d)},up:!0}),E.jsx(ll,{title:"Mode",index:s.indexOf(i),open:l,options:s,onSelect:d=>{if(d===i)return;const p=d;e.onSelectRenderMode(p),n(p)},onToggle:d=>{d&&h&&u(!1),r&&a(!1),c(d)},up:!0})]})]})}),lN=`out vec3 worldPosition;
|
|
485
|
+
*/const $e={LEFT:1,RIGHT:2,MIDDLE:4},F=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Gn={NONE:0,IN:1,OUT:-1};function Xi(o){return o.isPerspectiveCamera}function Ti(o){return o.isOrthographicCamera}const Vn=Math.PI*2,kf=Math.PI/2,qy=1e-5,$r=Math.PI/180;function ys(o,e,t){return Math.max(e,Math.min(t,o))}function Le(o,e=qy){return Math.abs(o)<e}function Ae(o,e,t=qy){return Le(o-e,t)}function zf(o,e){return Math.round(o/e)*e}function jr(o){return isFinite(o)?o:o<0?-Number.MAX_VALUE:Number.MAX_VALUE}function qr(o){return Math.abs(o)<Number.MAX_VALUE?o:o*(1/0)}function ba(o,e,t,s,i=1/0,n){s=Math.max(1e-4,s);const r=2/s,a=r*n,l=1/(1+a+.48*a*a+.235*a*a*a);let c=o-e;const h=e,u=i*s;c=ys(c,-u,u),e=o-c;const d=(t.value+r*c)*n;t.value=(t.value-r*d)*l;let p=e+(c+d)*l;return h-o>0==p>h&&(p=h,t.value=(p-h)/n),p}function Gf(o,e,t,s,i=1/0,n,r){s=Math.max(1e-4,s);const a=2/s,l=a*n,c=1/(1+l+.48*l*l+.235*l*l*l);let h=e.x,u=e.y,d=e.z,p=o.x-h,f=o.y-u,m=o.z-d;const x=h,g=u,_=d,b=i*s,T=b*b,S=p*p+f*f+m*m;if(S>T){const Z=Math.sqrt(S);p=p/Z*b,f=f/Z*b,m=m/Z*b}h=o.x-p,u=o.y-f,d=o.z-m;const C=(t.x+a*p)*n,w=(t.y+a*f)*n,R=(t.z+a*m)*n;t.x=(t.x-a*C)*c,t.y=(t.y-a*w)*c,t.z=(t.z-a*R)*c,r.x=h+(p+C)*c,r.y=u+(f+w)*c,r.z=d+(m+R)*c;const P=x-o.x,z=g-o.y,$=_-o.z,q=r.x-x,j=r.y-g,X=r.z-_;return P*q+z*j+$*X>0&&(r.x=x,r.y=g,r.z=_,t.x=(r.x-x)/n,t.y=(r.y-g)/n,t.z=(r.z-_)/n),r}function Jc(o,e){e.set(0,0),o.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=o.length,e.y/=o.length}function eh(o,e){return Ti(o)?(console.warn(`${e} is not supported in OrthographicCamera`),!0):!1}class RN{constructor(){this._listeners={}}addEventListener(e,t){const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){const s=this._listeners[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let n=0,r=i.length;n<r;n++)i[n].call(this,e)}}}var th;const NN="2.10.1",Ta=1/8,PN=/Mac/.test((th=globalThis?.navigator)===null||th===void 0?void 0:th.platform);let J,Vf,Sa,sh,Lt,le,Te,Hn,Yr,As,Rs,Zi,Hf,Wf,ts,Xr,Wn,$f,ih,jf,nh,rh,va;class Ds extends RN{static install(e){J=e.THREE,Vf=Object.freeze(new J.Vector3(0,0,0)),Sa=Object.freeze(new J.Vector3(0,1,0)),sh=Object.freeze(new J.Vector3(0,0,1)),Lt=new J.Vector2,le=new J.Vector3,Te=new J.Vector3,Hn=new J.Vector3,Yr=new J.Vector3,As=new J.Vector3,Rs=new J.Vector3,Zi=new J.Vector3,Hf=new J.Vector3,Wf=new J.Vector3,ts=new J.Spherical,Xr=new J.Spherical,Wn=new J.Box3,$f=new J.Box3,ih=new J.Sphere,jf=new J.Quaternion,nh=new J.Quaternion,rh=new J.Matrix4,va=new J.Raycaster}static get ACTION(){return F}set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(e,t){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=F.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Gn.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new J.Vector3,this._focalOffsetVelocity=new J.Vector3,this._zoomVelocity={value:0},this._truckInternal=(g,_,b,T)=>{let S,C;if(Xi(this._camera)){const w=le.copy(this._camera.position).sub(this._target),R=this._camera.getEffectiveFOV()*$r,P=w.length()*Math.tan(R*.5);S=this.truckSpeed*g*P/this._elementRect.height,C=this.truckSpeed*_*P/this._elementRect.height}else if(Ti(this._camera)){const w=this._camera;S=this.truckSpeed*g*(w.right-w.left)/w.zoom/this._elementRect.width,C=this.truckSpeed*_*(w.top-w.bottom)/w.zoom/this._elementRect.height}else return;T?(b?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(S,0,!0),this.forward(-C,!0)):b?this.setFocalOffset(this._focalOffsetEnd.x+S,this._focalOffsetEnd.y+C,this._focalOffsetEnd.z,!0):this.truck(S,C,!0)},this._rotateInternal=(g,_)=>{const b=Vn*this.azimuthRotateSpeed*g/this._elementRect.height,T=Vn*this.polarRotateSpeed*_/this._elementRect.height;this.rotate(b,T,!0)},this._dollyInternal=(g,_,b)=>{const T=Math.pow(.95,-g*this.dollySpeed),S=this._sphericalEnd.radius,C=this._sphericalEnd.radius*T,w=ys(C,this.minDistance,this.maxDistance),R=w-C;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(C,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(R,!0),this._dollyToNoClamp(w,!0)):this._dollyToNoClamp(w,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?C:w)-S,this._dollyControlCoord.set(_,b)),this._lastDollyDirection=Math.sign(-g)},this._zoomInternal=(g,_,b)=>{const T=Math.pow(.95,g*this.dollySpeed),S=this._zoom,C=this._zoom*T;this.zoomTo(C,!0),this.dollyToCursor&&(this._changedZoom+=C-S,this._dollyControlCoord.set(_,b))},typeof J>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new J.Quaternion().setFromUnitVectors(this._camera.up,Sa),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=F.NONE,this._target=new J.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new J.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new J.Spherical().setFromVector3(le.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new J.Vector3,new J.Vector3,new J.Vector3,new J.Vector3],this._updateNearPlaneCorners(),this._boundary=new J.Box3(new J.Vector3(-1/0,-1/0,-1/0),new J.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new J.Vector2,this.mouseButtons={left:F.ROTATE,middle:F.DOLLY,right:F.TRUCK,wheel:Xi(this._camera)?F.DOLLY:Ti(this._camera)?F.ZOOM:F.NONE},this.touches={one:F.TOUCH_ROTATE,two:Xi(this._camera)?F.TOUCH_DOLLY_TRUCK:Ti(this._camera)?F.TOUCH_ZOOM_TRUCK:F.NONE,three:F.TOUCH_TRUCK};const s=new J.Vector2,i=new J.Vector2,n=new J.Vector2,r=g=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const T=this._domElement.getBoundingClientRect(),S=g.clientX/T.width,C=g.clientY/T.height;if(S<this._interactiveArea.left||S>this._interactiveArea.right||C<this._interactiveArea.top||C>this._interactiveArea.bottom)return}const _=g.pointerType!=="mouse"?null:(g.buttons&$e.LEFT)===$e.LEFT?$e.LEFT:(g.buttons&$e.MIDDLE)===$e.MIDDLE?$e.MIDDLE:(g.buttons&$e.RIGHT)===$e.RIGHT?$e.RIGHT:null;if(_!==null){const T=this._findPointerByMouseButton(_);T&&this._disposePointer(T)}if((g.buttons&$e.LEFT)===$e.LEFT&&this._lockedPointer)return;const b={pointerId:g.pointerId,clientX:g.clientX,clientY:g.clientY,deltaX:0,deltaY:0,mouseButton:_};this._activePointers.push(b),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.addEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),this._isDragging=!0,d(g)},a=g=>{g.cancelable&&g.preventDefault();const _=g.pointerId,b=this._lockedPointer||this._findPointerById(_);if(b){if(b.clientX=g.clientX,b.clientY=g.clientY,b.deltaX=g.movementX,b.deltaY=g.movementY,this._state=0,g.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(g.buttons&$e.LEFT)===$e.LEFT)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(g.buttons&$e.MIDDLE)===$e.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(g.buttons&$e.RIGHT)===$e.RIGHT&&(this._state=this._state|this.mouseButtons.right);p()}},l=g=>{const _=this._findPointerById(g.pointerId);if(!(_&&_===this._lockedPointer)){if(_&&this._disposePointer(_),g.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=F.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=F.NONE;f()}};let c=-1;const h=g=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===F.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){const C=this._domElement.getBoundingClientRect(),w=g.clientX/C.width,R=g.clientY/C.height;if(w<this._interactiveArea.left||w>this._interactiveArea.right||R<this._interactiveArea.top||R>this._interactiveArea.bottom)return}if(g.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===F.ROTATE||this.mouseButtons.wheel===F.TRUCK){const C=performance.now();c-C<1e3&&this._getClientRect(this._elementRect),c=C}const _=PN?-1:-3,b=g.deltaMode===1||g.ctrlKey?g.deltaY/_:g.deltaY/(_*10),T=this.dollyToCursor?(g.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,S=this.dollyToCursor?(g.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case F.ROTATE:{this._rotateInternal(g.deltaX,g.deltaY),this._isUserControllingRotate=!0;break}case F.TRUCK:{this._truckInternal(g.deltaX,g.deltaY,!1,!1),this._isUserControllingTruck=!0;break}case F.SCREEN_PAN:{this._truckInternal(g.deltaX,g.deltaY,!1,!0),this._isUserControllingTruck=!0;break}case F.OFFSET:{this._truckInternal(g.deltaX,g.deltaY,!0,!1),this._isUserControllingOffset=!0;break}case F.DOLLY:{this._dollyInternal(-b,T,S),this._isUserControllingDolly=!0;break}case F.ZOOM:{this._zoomInternal(-b,T,S),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},u=g=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===Ds.ACTION.NONE){const _=g instanceof PointerEvent?g.pointerId:0,b=this._findPointerById(_);b&&this._disposePointer(b),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l);return}g.preventDefault()}},d=g=>{if(!this._enabled)return;if(Jc(this._activePointers,Lt),this._getClientRect(this._elementRect),s.copy(Lt),i.copy(Lt),this._activePointers.length>=2){const b=Lt.x-this._activePointers[1].clientX,T=Lt.y-this._activePointers[1].clientY,S=Math.sqrt(b*b+T*T);n.set(0,S);const C=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,w=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(C,w)}if(this._state=0,!g)this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);else if("pointerType"in g&&g.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else!this._lockedPointer&&(g.buttons&$e.LEFT)===$e.LEFT&&(this._state=this._state|this.mouseButtons.left),(g.buttons&$e.MIDDLE)===$e.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(g.buttons&$e.RIGHT)===$e.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&F.ROTATE)===F.ROTATE||(this._state&F.TOUCH_ROTATE)===F.TOUCH_ROTATE||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&F.TRUCK)===F.TRUCK||(this._state&F.SCREEN_PAN)===F.SCREEN_PAN||(this._state&F.TOUCH_TRUCK)===F.TOUCH_TRUCK||(this._state&F.TOUCH_SCREEN_PAN)===F.TOUCH_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&F.DOLLY)===F.DOLLY||(this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&F.ZOOM)===F.ZOOM||(this._state&F.TOUCH_ZOOM)===F.TOUCH_ZOOM||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&F.OFFSET)===F.OFFSET||(this._state&F.TOUCH_OFFSET)===F.TOUCH_OFFSET||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Jc(this._activePointers,Lt);const _=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,b=_?-_.deltaX:i.x-Lt.x,T=_?-_.deltaY:i.y-Lt.y;if(i.copy(Lt),((this._state&F.ROTATE)===F.ROTATE||(this._state&F.TOUCH_ROTATE)===F.TOUCH_ROTATE||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(b,T),this._isUserControllingRotate=!0),(this._state&F.DOLLY)===F.DOLLY||(this._state&F.ZOOM)===F.ZOOM){const S=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,C=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0,w=this.dollyDragInverted?-1:1;(this._state&F.DOLLY)===F.DOLLY?(this._dollyInternal(w*T*Ta,S,C),this._isUserControllingDolly=!0):(this._zoomInternal(w*T*Ta,S,C),this._isUserControllingZoom=!0)}if((this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_ZOOM)===F.TOUCH_ZOOM||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_ZOOM_ROTATE)===F.TOUCH_ZOOM_ROTATE){const S=Lt.x-this._activePointers[1].clientX,C=Lt.y-this._activePointers[1].clientY,w=Math.sqrt(S*S+C*C),R=n.y-w;n.set(0,w);const P=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,z=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&F.TOUCH_DOLLY)===F.TOUCH_DOLLY||(this._state&F.TOUCH_DOLLY_ROTATE)===F.TOUCH_DOLLY_ROTATE||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET?(this._dollyInternal(R*Ta,P,z),this._isUserControllingDolly=!0):(this._zoomInternal(R*Ta,P,z),this._isUserControllingZoom=!0)}((this._state&F.TRUCK)===F.TRUCK||(this._state&F.TOUCH_TRUCK)===F.TOUCH_TRUCK||(this._state&F.TOUCH_DOLLY_TRUCK)===F.TOUCH_DOLLY_TRUCK||(this._state&F.TOUCH_ZOOM_TRUCK)===F.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(b,T,!1,!1),this._isUserControllingTruck=!0),((this._state&F.SCREEN_PAN)===F.SCREEN_PAN||(this._state&F.TOUCH_SCREEN_PAN)===F.TOUCH_SCREEN_PAN||(this._state&F.TOUCH_DOLLY_SCREEN_PAN)===F.TOUCH_DOLLY_SCREEN_PAN||(this._state&F.TOUCH_ZOOM_SCREEN_PAN)===F.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(b,T,!1,!0),this._isUserControllingTruck=!0),((this._state&F.OFFSET)===F.OFFSET||(this._state&F.TOUCH_OFFSET)===F.TOUCH_OFFSET||(this._state&F.TOUCH_DOLLY_OFFSET)===F.TOUCH_DOLLY_OFFSET||(this._state&F.TOUCH_ZOOM_OFFSET)===F.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(b,T,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},f=()=>{Jc(this._activePointers,Lt),i.copy(Lt),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",m),this._domElement.ownerDocument.addEventListener("pointerlockerror",x),this._domElement.ownerDocument.addEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",l),d())},this.unlockPointer=()=>{var g,_,b;this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),(g=this._domElement)===null||g===void 0||g.ownerDocument.exitPointerLock(),(_=this._domElement)===null||_===void 0||_.ownerDocument.removeEventListener("pointerlockchange",m),(b=this._domElement)===null||b===void 0||b.ownerDocument.removeEventListener("pointerlockerror",x),this.cancel()};const m=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},x=()=>{this.unlockPointer()};this._addAllEventListeners=g=>{this._domElement=g,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",l),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",u)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",l),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",u),this._domElement.ownerDocument.removeEventListener("pointermove",a,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",l),this._domElement.ownerDocument.removeEventListener("pointerlockchange",m),this._domElement.ownerDocument.removeEventListener("pointerlockerror",x))},this.cancel=()=>{this._state!==F.NONE&&(this._state=F.NONE,this._activePointers.length=0,f())},t&&this.connect(t),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=ys(e.width,0,1),this._interactiveArea.height=ys(e.height,0,1),this._interactiveArea.x=ys(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=ys(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,s)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,s=!1){this._isUserControllingRotate=!1;const i=ys(e,this.minAzimuthAngle,this.maxAzimuthAngle),n=ys(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=i,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!s||Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Gn.NONE,this._changedDolly=0,this._dollyToNoClamp(ys(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){const s=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const r=this._collisionTest(),a=Ae(r,this._spherical.radius);if(!(s>e)&&a)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,r)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);const n=!t||Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(n)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(Yr).multiplyScalar(e)),t||this._target.copy(this._targetEnd);const s=!t||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(s)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=ys(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);const s=!t||Ae(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(s)}pan(e,t,s=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,s)}truck(e,t,s=!1){this._camera.updateMatrix(),As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),As.multiplyScalar(e),Rs.multiplyScalar(-t);const i=le.copy(As).add(Rs),n=Te.copy(this._targetEnd).add(i);return this.moveTo(n.x,n.y,n.z,s)}forward(e,t=!1){le.setFromMatrixColumn(this._camera.matrix,0),le.crossVectors(this._camera.up,le),le.multiplyScalar(e);const s=Te.copy(this._targetEnd).add(le);return this.moveTo(s.x,s.y,s.z,t)}elevate(e,t=!1){return le.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+le.x,this._targetEnd.y+le.y,this._targetEnd.z+le.z,t)}moveTo(e,t,s,i=!1){this._isUserControllingTruck=!1;const n=le.set(e,t,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,i||this._target.copy(this._targetEnd);const r=!i||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(e,t,s,i=!1){const a=le.set(e,t,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(a.x,a.y,a.z,i)}fitToBox(e,t,{cover:s=!1,paddingLeft:i=0,paddingRight:n=0,paddingBottom:r=0,paddingTop:a=0}={}){const l=[],c=e.isBox3?Wn.copy(e):Wn.setFromObject(e);c.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=zf(this._sphericalEnd.theta,kf),u=zf(this._sphericalEnd.phi,kf);l.push(this.rotateTo(h,u,t));const d=le.setFromSpherical(this._sphericalEnd).normalize(),p=jf.setFromUnitVectors(d,sh),f=Ae(Math.abs(d.y),1);f&&p.multiply(nh.setFromAxisAngle(Sa,h)),p.multiply(this._yAxisUpSpaceInverse);const m=$f.makeEmpty();Te.copy(c.min).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setX(c.max.x).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setY(c.max.y).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setZ(c.min.z).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.min).setZ(c.max.z).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setY(c.min.y).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).setX(c.min.x).applyQuaternion(p),m.expandByPoint(Te),Te.copy(c.max).applyQuaternion(p),m.expandByPoint(Te),m.min.x-=i,m.min.y-=r,m.max.x+=n,m.max.y+=a,p.setFromUnitVectors(sh,d),f&&p.premultiply(nh.invert()),p.premultiply(this._yAxisUpSpace);const x=m.getSize(le),g=m.getCenter(Te).applyQuaternion(p);if(Xi(this._camera)){const _=this.getDistanceToFitBox(x.x,x.y,x.z,s);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.dollyTo(_,t)),l.push(this.setFocalOffset(0,0,0,t))}else if(Ti(this._camera)){const _=this._camera,b=_.right-_.left,T=_.top-_.bottom,S=s?Math.max(b/x.x,T/x.y):Math.min(b/x.x,T/x.y);l.push(this.moveTo(g.x,g.y,g.z,t)),l.push(this.zoomTo(S,t)),l.push(this.setFocalOffset(0,0,0,t))}return Promise.all(l)}fitToSphere(e,t){const s=[],n="isObject3D"in e?Ds.createBoundingSphere(e,ih):ih.copy(e);if(s.push(this.moveTo(n.center.x,n.center.y,n.center.z,t)),Xi(this._camera)){const r=this.getDistanceToFitSphere(n.radius);s.push(this.dollyTo(r,t))}else if(Ti(this._camera)){const r=this._camera.right-this._camera.left,a=this._camera.top-this._camera.bottom,l=2*n.radius,c=Math.min(r/l,a/l);s.push(this.zoomTo(c,t))}return s.push(this.setFocalOffset(0,0,0,t)),Promise.all(s)}setLookAt(e,t,s,i,n,r,a=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Gn.NONE,this._changedDolly=0;const l=Te.set(i,n,r),c=le.set(e,t,s);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(c.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,a||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!a||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold)&&Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(e,t,s,i,n,r,a,l,c,h,u,d,p,f=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Gn.NONE,this._changedDolly=0;const m=le.set(i,n,r),x=Te.set(e,t,s);ts.setFromVector3(x.sub(m).applyQuaternion(this._yAxisUpSpace));const g=Hn.set(h,u,d),_=Te.set(a,l,c);Xr.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(m.lerp(g,p));const b=Xr.theta-ts.theta,T=Xr.phi-ts.phi,S=Xr.radius-ts.radius;this._sphericalEnd.set(ts.radius+S*p,ts.phi+T*p,ts.theta+b*p),this.normalizeRotations(),this._needsUpdate=!0,f||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const C=!f||Ae(this._target.x,this._targetEnd.x,this.restThreshold)&&Ae(this._target.y,this._targetEnd.y,this.restThreshold)&&Ae(this._target.z,this._targetEnd.z,this.restThreshold)&&Ae(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ae(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ae(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(C)}setPosition(e,t,s,i=!1){return this.setLookAt(e,t,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,i)}setTarget(e,t,s,i=!1){const n=this.getPosition(le),r=this.setLookAt(n.x,n.y,n.z,e,t,s,i);return this._sphericalEnd.phi=ys(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(e,t,s,i=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,s),this._needsUpdate=!0,i||this._focalOffset.copy(this._focalOffsetEnd);const n=!i||Ae(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ae(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ae(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(e,t,s){this._camera.updateMatrixWorld(),As.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Rs.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Zi.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const i=le.set(e,t,s),n=i.distanceTo(this._camera.position),r=i.sub(this._camera.position);As.multiplyScalar(r.x),Rs.multiplyScalar(r.y),Zi.multiplyScalar(r.z),le.copy(As).add(Rs).add(Zi),le.z=le.z+n,this.dollyTo(n,!1),this.setFocalOffset(-le.x,le.y,-le.z,!1),this.moveTo(e,t,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,s,i){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new J.Vector4,typeof e=="number"?this._viewport.set(e,t,s,i):this._viewport.copy(e)}getDistanceToFitBox(e,t,s,i=!1){if(eh(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=e/t,r=this._camera.getEffectiveFOV()*$r,a=this._camera.aspect;return((i?n>a:n<a)?t:e/a)*.5/Math.tan(r*.5)+s*.5}getDistanceToFitSphere(e){if(eh(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const t=this._camera.getEffectiveFOV()*$r,s=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,i=1<this._camera.aspect?t:s;return e/Math.sin(i*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new J.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new J.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Vn,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Vn),this._spherical.theta+=Vn*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Vn)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Ae(this._camera.up.x,this._cameraUp0.x)||!Ae(this._camera.up.y,this._cameraUp0.y)||!Ae(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const s=this.getPosition(le);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}const t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Sa),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const e=le.subVectors(this._target,this._camera.position).normalize(),t=Te.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();const s=this.getPosition(le);this.updateCameraUp(),this.setPosition(s.x,s.y,s.z)}update(e){const t=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,i=this._sphericalEnd.radius-this._spherical.radius,n=Hf.subVectors(this._targetEnd,this._target),r=Wf.subVectors(this._focalOffsetEnd,this._focalOffset),a=this._zoomEnd-this._zoom;if(Le(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=ba(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,e),this._needsUpdate=!0}if(Le(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=ba(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,e),this._needsUpdate=!0}if(Le(i))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=ba(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,e),this._needsUpdate=!0}if(Le(n.x)&&Le(n.y)&&Le(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Gf(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(Le(r.x)&&Le(r.y)&&Le(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Gf(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(Le(a))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=ba(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,e)}if(this.dollyToCursor){if(Xi(this._camera)&&this._changedDolly!==0){const u=this._spherical.radius-this._lastDistance,d=this._camera,p=this._getCameraDirection(Yr),f=le.copy(p).cross(d.up).normalize();f.lengthSq()===0&&(f.x=1);const m=Te.crossVectors(f,p),x=this._sphericalEnd.radius*Math.tan(d.getEffectiveFOV()*$r*.5),_=(this._sphericalEnd.radius-u-this._sphericalEnd.radius)/this._sphericalEnd.radius,b=Hn.copy(this._targetEnd).add(f.multiplyScalar(this._dollyControlCoord.x*x*d.aspect)).add(m.multiplyScalar(this._dollyControlCoord.y*x)),T=le.copy(this._targetEnd).lerp(b,_),S=this._lastDollyDirection===Gn.IN&&this._spherical.radius<=this.minDistance,C=this._lastDollyDirection===Gn.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(S||C)){this._sphericalEnd.radius-=u,this._spherical.radius-=u;const R=Te.copy(p).multiplyScalar(-u);T.add(R)}this._boundary.clampPoint(T,T);const w=Te.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(w),this._changedDolly-=u,Le(this._changedDolly)&&(this._changedDolly=0)}else if(Ti(this._camera)&&this._changedZoom!==0){const u=this._zoom-this._lastZoom,d=this._camera,p=le.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(d.near+d.far)/(d.near-d.far)).unproject(d),f=Te.set(0,0,-1).applyQuaternion(d.quaternion),m=Hn.copy(p).add(f.multiplyScalar(-p.dot(d.up))),g=-(this._zoom-u-this._zoom)/this._zoom,_=this._getCameraDirection(Yr),b=this._targetEnd.dot(_),T=le.copy(this._targetEnd).lerp(m,g),S=T.dot(_),C=_.multiplyScalar(S-b);T.sub(C),this._boundary.clampPoint(T,T);const w=Te.subVectors(T,this._targetEnd);this._targetEnd.copy(T),this._target.add(w),this._changedZoom-=u,Le(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const l=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,l),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!Le(this._focalOffset.x)||!Le(this._focalOffset.y)||!Le(this._focalOffset.z))&&(As.setFromMatrixColumn(this._camera.matrix,0),Rs.setFromMatrixColumn(this._camera.matrix,1),Zi.setFromMatrixColumn(this._camera.matrix,2),As.multiplyScalar(this._focalOffset.x),Rs.multiplyScalar(-this._focalOffset.y),Zi.multiplyScalar(this._focalOffset.z),le.copy(As).add(Rs).add(Zi),this._camera.position.add(le),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),le.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const h=this._needsUpdate;return h&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):h?(this.dispatchEvent({type:"update"}),Le(t,this.restThreshold)&&Le(s,this.restThreshold)&&Le(i,this.restThreshold)&&Le(n.x,this.restThreshold)&&Le(n.y,this.restThreshold)&&Le(n.z,this.restThreshold)&&Le(r.x,this.restThreshold)&&Le(r.y,this.restThreshold)&&Le(r.z,this.restThreshold)&&Le(a,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!h&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=h,this._needsUpdate=!1,h}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:jr(this.maxDistance),minZoom:this.minZoom,maxZoom:jr(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:jr(this.maxPolarAngle),minAzimuthAngle:jr(this.minAzimuthAngle),maxAzimuthAngle:jr(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:le.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){const s=JSON.parse(e);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=qr(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=qr(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=qr(s.maxPolarAngle),this.minAzimuthAngle=qr(s.minAzimuthAngle),this.maxAzimuthAngle=qr(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],t),ts.setFromVector3(le.fromArray(s.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ts.theta,ts.phi,t),this.dollyTo(ts.radius,t),this.zoomTo(s.zoom,t),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}e.setAttribute("data-camera-controls-version",NN),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,s){const i=t.lengthSq();if(i===0)return e;const n=Te.copy(t).add(e),a=this._boundary.clampPoint(n,Hn).sub(n),l=a.lengthSq();if(l===0)return e.add(t);if(l===i)return e;if(s===0)return e.add(t).add(a);{const c=1+s*l/t.dot(a);return e.add(Te.copy(t).multiplyScalar(c)).add(a.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(Xi(this._camera)){const e=this._camera,t=e.near,s=e.getEffectiveFOV()*$r,i=Math.tan(s*.5)*t,n=i*e.aspect;this._nearPlaneCorners[0].set(-n,-i,0),this._nearPlaneCorners[1].set(n,-i,0),this._nearPlaneCorners[2].set(n,i,0),this._nearPlaneCorners[3].set(-n,i,0)}else if(Ti(this._camera)){const e=this._camera,t=1/e.zoom,s=e.left*t,i=e.right*t,n=e.top*t,r=e.bottom*t;this._nearPlaneCorners[0].set(s,n,0),this._nearPlaneCorners[1].set(i,n,0),this._nearPlaneCorners[2].set(i,r,0),this._nearPlaneCorners[3].set(s,r,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||eh(this._camera,"_collisionTest"))return e;const s=this._getTargetDirection(Yr);rh.lookAt(Vf,s,this._camera.up);for(let i=0;i<4;i++){const n=Te.copy(this._nearPlaneCorners[i]);n.applyMatrix4(rh);const r=Hn.addVectors(this._target,n);va.set(r,s),va.far=this._spherical.radius+1;const a=va.intersectObjects(this.colliderMeshes);a.length!==0&&a[0].distance<e&&(e=a[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const s=()=>{this.removeEventListener("rest",s),t()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(e){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(e){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(e,t=new J.Sphere){const s=t,i=s.center;Wn.makeEmpty(),e.traverseVisible(r=>{r.isMesh&&Wn.expandByObject(r)}),Wn.getCenter(i);let n=0;return e.traverseVisible(r=>{if(!r.isMesh)return;const a=r;if(!a.geometry)return;const l=a.geometry.clone();l.applyMatrix4(a.matrixWorld);const h=l.attributes.position;for(let u=0,d=h.count;u<d;u++)le.fromBufferAttribute(h,u),n=Math.max(n,i.distanceToSquared(le))}),s.radius=Math.sqrt(n),s}}const hl=o=>{const[e,t]=W.useState(o.options[o.index]),s=()=>{o.onToggle(!o.open)},i=r=>{r!==e&&(o.onSelect(r),t(r)),o.onToggle(!1)},n=o.open?`${o.options.length*31-1}px`:"0px";return E.jsxs("div",{className:`dropdown ${o.up===!0?"up":""}`,children:[E.jsx("div",{className:"dropdown-toggle",onClick:s,children:`${o.title}: ${e}`}),E.jsx("ul",{className:"dropdown-menu",style:{height:n},children:o.options.map(r=>E.jsx("li",{onClick:()=>i(r),children:r},r))})]})},Ki=W.forwardRef(function(e,t){const s=["Renderer","Depth","Normals","UVs","Wireframe"],[i,n]=W.useState("Renderer"),[r,a]=W.useState(!1),[l,c]=W.useState(!1),[h,u]=W.useState(!1);return E.jsxs("div",{className:`CameraWindow ${e.name}`,children:[E.jsx("div",{ref:t,className:"clickable",onClick:()=>{h&&u(!1)}}),E.jsxs("div",{className:"options",children:[e.camera!==null&&E.jsx(hl,{title:"Camera",index:e.options.indexOf(e.camera.name),open:h,options:e.options,onSelect:e.onSelectCamera,onToggle:d=>{d&&l&&c(!1),u(d)},up:!0}),E.jsx(hl,{title:"Mode",index:s.indexOf(i),open:l,options:s,onSelect:d=>{if(d===i)return;const p=d;e.onSelectRenderMode(p),n(p)},onToggle:d=>{d&&h&&u(!1),r&&a(!1),c(d)},up:!0})]})]})}),FN=`out vec3 worldPosition;
|
|
486
486
|
uniform float uDistance;
|
|
487
487
|
|
|
488
488
|
void main() {
|
|
@@ -491,7 +491,7 @@ void main() {
|
|
|
491
491
|
worldPosition.xz += cameraPosition.xz;
|
|
492
492
|
|
|
493
493
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(worldPosition, 1.0);
|
|
494
|
-
}`,
|
|
494
|
+
}`,DN=`out vec4 fragColor;
|
|
495
495
|
in vec3 worldPosition;
|
|
496
496
|
uniform float uDivisions;
|
|
497
497
|
uniform float uScale;
|
|
@@ -559,7 +559,7 @@ void main() {
|
|
|
559
559
|
fragColor.a = mix(fragColor.a, baseOpacity * uGridOpacity, nextGrid);
|
|
560
560
|
|
|
561
561
|
if (fragColor.a <= minAlpha) discard;
|
|
562
|
-
}`;class
|
|
562
|
+
}`;class Yy extends y.ShaderMaterial{constructor(e){super({extensions:{derivatives:!0},uniforms:{uScale:{value:e?.scale!==void 0?e?.scale:.1},uDivisions:{value:e?.divisions!==void 0?e?.divisions:10},uColor:{value:e?.color!==void 0?e?.color:new y.Color(16777215)},uDistance:{value:e?.distance!==void 0?e?.distance:1e4},uSubgridOpacity:{value:e?.subgridOpacity!==void 0?e?.subgridOpacity:.15},uGridOpacity:{value:e?.gridOpacity!==void 0?e?.gridOpacity:.25}},glslVersion:y.GLSL3,side:y.DoubleSide,transparent:!0,name:"InfiniteGrid",vertexShader:FN,fragmentShader:DN})}}class Xy extends y.Mesh{gridMaterial;constructor(e){const t=new Yy(e);super(new y.PlaneGeometry,t),this.gridMaterial=t,this.frustumCulled=!1,this.name="InfiniteGridHelper"}update(){this.gridMaterial.needsUpdate=!0}}function oh(o){const[e,t]=W.useState(o.selected),s="toggle"+(e?" selected":"");return E.jsx("button",{className:s,onClick:()=>{const i=!e;t(i),o.onClick(i)},style:{backgroundImage:`url(${o.icon})`,backgroundPositionX:"center",backgroundPositionY:o.top!==void 0?`${o.top}px`:"center",backgroundSize:`${o.width!==void 0?`${o.width}px`:"26px"} ${o.height}px`}},o.name)}const ON=`#include <common>
|
|
563
563
|
#include <batching_pars_vertex>
|
|
564
564
|
#include <uv_pars_vertex>
|
|
565
565
|
#include <color_pars_vertex>
|
|
@@ -589,7 +589,7 @@ void main() {
|
|
|
589
589
|
#include <logdepthbuf_vertex>
|
|
590
590
|
#include <clipping_planes_vertex>
|
|
591
591
|
#include <worldpos_vertex>
|
|
592
|
-
}`,
|
|
592
|
+
}`,BN=`
|
|
593
593
|
#include <common>
|
|
594
594
|
#include <uv_pars_fragment>
|
|
595
595
|
#include <clipping_planes_pars_fragment>
|
|
@@ -597,4 +597,4 @@ void main() {
|
|
|
597
597
|
void main() {
|
|
598
598
|
#include <clipping_planes_fragment>
|
|
599
599
|
gl_FragColor = vec4(vec3(vUv, 0.0), 1.0);
|
|
600
|
-
}`;class jy extends x.ShaderMaterial{constructor(){super({defines:{USE_UV:""},vertexShader:hN,fragmentShader:uN})}}const Ki=new x.Raycaster,_t=new x.Vector3,bi=new x.Vector3,He=new x.Quaternion,Wf={X:new x.Vector3(1,0,0),Y:new x.Vector3(0,1,0),Z:new x.Vector3(0,0,1)},nh={type:"change"},$f={type:"mouseDown",mode:null},jf={type:"mouseUp",mode:null},qf={type:"objectChange"};class dN extends x.Controls{constructor(e,t=null){super(void 0,t);const s=new xN(this);this._root=s;const i=new _N;this._gizmo=i,s.add(i);const n=new bN;this._plane=n,s.add(n);const r=this;function a(b,T){let S=T;Object.defineProperty(r,b,{get:function(){return S!==void 0?S:T},set:function(C){S!==C&&(S=C,n[b]=C,i[b]=C,r.dispatchEvent({type:b+"-changed",value:C}),r.dispatchEvent(nh))}}),r[b]=T,n[b]=T,i[b]=T}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new x.Vector3,c=new x.Vector3,h=new x.Quaternion,u=new x.Quaternion,d=new x.Vector3,p=new x.Quaternion,f=new x.Vector3,m=new x.Vector3,y=new x.Vector3,g=0,_=new x.Vector3;a("worldPosition",l),a("worldPositionStart",c),a("worldQuaternion",h),a("worldQuaternionStart",u),a("cameraPosition",d),a("cameraQuaternion",p),a("pointStart",f),a("pointEnd",m),a("rotationAxis",y),a("rotationAngle",g),a("eye",_),this._offset=new x.Vector3,this._startNorm=new x.Vector3,this._endNorm=new x.Vector3,this._cameraScale=new x.Vector3,this._parentPosition=new x.Vector3,this._parentQuaternion=new x.Quaternion,this._parentQuaternionInv=new x.Quaternion,this._parentScale=new x.Vector3,this._worldScaleStart=new x.Vector3,this._worldQuaternionInv=new x.Quaternion,this._worldScale=new x.Vector3,this._positionStart=new x.Vector3,this._quaternionStart=new x.Quaternion,this._scaleStart=new x.Vector3,this._getPointer=pN.bind(this),this._onPointerDown=mN.bind(this),this._onPointerHover=fN.bind(this),this._onPointerMove=gN.bind(this),this._onPointerUp=yN.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&Ki.setFromCamera(e,this.camera);const t=rh(this._gizmo.picker[this.mode],Ki);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&Ki.setFromCamera(e,this.camera);const t=rh(this._plane,Ki,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,$f.mode=this.mode,this.dispatchEvent($f)}}pointerMove(e){const t=this.axis,s=this.mode,i=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),i===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&Ki.setFromCamera(e,this.camera);const r=rh(this._plane,Ki,!0);if(r){if(this.pointEnd.copy(r.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(i.position.applyQuaternion(He.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),n==="world"&&(i.parent&&i.position.add(_t.setFromMatrixPosition(i.parent.matrixWorld)),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(_t.setFromMatrixPosition(i.parent.matrixWorld)))),i.position.x=Math.max(this.minX,Math.min(this.maxX,i.position.x)),i.position.y=Math.max(this.minY,Math.min(this.maxY,i.position.y)),i.position.z=Math.max(this.minZ,Math.min(this.maxZ,i.position.z));else if(s==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),bi.set(a,a,a)}else _t.copy(this.pointStart),bi.copy(this.pointEnd),_t.applyQuaternion(this._worldQuaternionInv),bi.applyQuaternion(this._worldQuaternionInv),bi.divide(_t),t.search("X")===-1&&(bi.x=1),t.search("Y")===-1&&(bi.y=1),t.search("Z")===-1&&(bi.z=1);i.scale.copy(this._scaleStart).multiply(bi),this.scaleSnap&&(t.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(_t.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(_t.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(Wf[t]),_t.copy(Wf[t]),n==="local"&&_t.applyQuaternion(this.worldQuaternion),_t.cross(this.eye),_t.length()===0?l=!0:this.rotationAngle=this._offset.dot(_t.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(He.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(He.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(nh),this.dispatchEvent(qf)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(jf.mode=this.mode,this.dispatchEvent(jf)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(nh),this.dispatchEvent(qf),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Ki}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function pN(o){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:o.button};{const e=this.domElement.getBoundingClientRect();return{x:(o.clientX-e.left)/e.width*2-1,y:-(o.clientY-e.top)/e.height*2+1,button:o.button}}}function fN(o){if(this.enabled)switch(o.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(o));break}}function mN(o){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(o)),this.pointerDown(this._getPointer(o)))}function gN(o){this.enabled&&this.pointerMove(this._getPointer(o))}function yN(o){this.enabled&&(this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(o)))}function rh(o,e,t){const s=e.intersectObject(o,!0);for(let i=0;i<s.length;i++)if(s[i].object.visible||t)return s[i];return!1}const va=new x.Euler,Oe=new x.Vector3(0,1,0),Yf=new x.Vector3(0,0,0),Xf=new x.Matrix4,wa=new x.Quaternion,Ua=new x.Quaternion,Ns=new x.Vector3,Zf=new x.Matrix4,io=new x.Vector3(1,0,0),nn=new x.Vector3(0,1,0),no=new x.Vector3(0,0,1),Ma=new x.Vector3,Yr=new x.Vector3,Xr=new x.Vector3;class xN extends x.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;t.object!==void 0&&(t.object.updateMatrixWorld(),t.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class _N extends x.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new x.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new x.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const i=t.clone();i.opacity=.5;const n=e.clone();n.color.setHex(16711680);const r=e.clone();r.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const u=e.clone();u.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const m=new x.CylinderGeometry(0,.04,.1,12);m.translate(0,.05,0);const y=new x.BoxGeometry(.08,.08,.08);y.translate(0,.04,0);const g=new x.BufferGeometry;g.setAttribute("position",new x.Float32BufferAttribute([0,0,0,1,0,0],3));const _=new x.CylinderGeometry(.0075,.0075,.5,3);_.translate(0,.25,0);function b(Z,we){const ue=new x.TorusGeometry(Z,.0075,3,64,we*Math.PI*2);return ue.rotateY(Math.PI/2),ue.rotateX(Math.PI/2),ue}function T(){const Z=new x.BufferGeometry;return Z.setAttribute("position",new x.Float32BufferAttribute([0,0,0,1,1,1],3)),Z}const S={X:[[new x.Mesh(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new x.Mesh(m,n),[-.5,0,0],[0,0,Math.PI/2]],[new x.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new x.Mesh(m,r),[0,.5,0]],[new x.Mesh(m,r),[0,-.5,0],[Math.PI,0,0]],[new x.Mesh(_,r)]],Z:[[new x.Mesh(m,a),[0,0,.5],[Math.PI/2,0,0]],[new x.Mesh(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new x.Mesh(_,a),null,[Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.OctahedronGeometry(.1,0),u.clone()),[0,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),h.clone()),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},C={X:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.OctahedronGeometry(.2,0),s)]],XY:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},w={START:[[new x.Mesh(new x.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],END:[[new x.Mesh(new x.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],DELTA:[[new x.Line(T(),i),null,null,null,"helper"]],X:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new x.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new x.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},R={XYZE:[[new x.Mesh(b(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new x.Mesh(b(.5,.5),n)]],Y:[[new x.Mesh(b(.5,.5),r),null,[0,0,-Math.PI/2]]],Z:[[new x.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new x.Mesh(b(.75,1),d),null,[0,Math.PI/2,0]]]},P={AXIS:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},z={XYZE:[[new x.Mesh(new x.SphereGeometry(.25,10,8),s)]],X:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new x.Mesh(new x.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new x.Mesh(new x.TorusGeometry(.75,.1,2,24),s)]]},$={X:[[new x.Mesh(y,n),[.5,0,0],[0,0,-Math.PI/2]],[new x.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]],[new x.Mesh(y,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(y,r),[0,.5,0]],[new x.Mesh(_,r)],[new x.Mesh(y,r),[0,-.5,0],[0,0,Math.PI]]],Z:[[new x.Mesh(y,a),[0,0,.5],[Math.PI/2,0,0]],[new x.Mesh(_,a),[0,0,0],[Math.PI/2,0,0]],[new x.Mesh(y,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.BoxGeometry(.1,.1,.1),u.clone())]]},q={X:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new x.Mesh(new x.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new x.Mesh(new x.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},j={X:[[new x.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new x.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new x.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function X(Z){const we=new x.Object3D;for(const ue in Z)for(let ye=Z[ue].length;ye--;){const se=Z[ue][ye][0].clone(),Me=Z[ue][ye][1],ze=Z[ue][ye][2],ot=Z[ue][ye][3],be=Z[ue][ye][4];se.name=ue,se.tag=be,Me&&se.position.set(Me[0],Me[1],Me[2]),ze&&se.rotation.set(ze[0],ze[1],ze[2]),ot&&se.scale.set(ot[0],ot[1],ot[2]),se.updateMatrix();const at=se.geometry.clone();at.applyMatrix4(se.matrix),se.geometry=at,se.renderOrder=1/0,se.position.set(0,0,0),se.rotation.set(0,0,0),se.scale.set(1,1,1),we.add(se)}return we}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=X(S)),this.add(this.gizmo.rotate=X(R)),this.add(this.gizmo.scale=X($)),this.add(this.picker.translate=X(C)),this.add(this.picker.rotate=X(z)),this.add(this.picker.scale=X(q)),this.add(this.helper.translate=X(w)),this.add(this.helper.rotate=X(P)),this.add(this.helper.scale=X(j)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const s=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Ua;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let n=0;n<i.length;n++){const r=i[n];r.visible=!0,r.rotation.set(0,0,0),r.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),r.scale.set(1,1,1).multiplyScalar(a*this.size/4),r.tag==="helper"){r.visible=!1,r.name==="AXIS"?(r.visible=!!this.axis,this.axis==="X"&&(He.setFromEuler(va.set(0,0,0)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(io).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Y"&&(He.setFromEuler(va.set(0,0,Math.PI/2)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Z"&&(He.setFromEuler(va.set(0,Math.PI/2,0)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(no).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="XYZE"&&(He.setFromEuler(va.set(0,Math.PI/2,0)),Oe.copy(this.rotationAxis),r.quaternion.setFromRotationMatrix(Xf.lookAt(Yf,Oe,nn)),r.quaternion.multiply(He),r.visible=this.dragging),this.axis==="E"&&(r.visible=!1)):r.name==="START"?(r.position.copy(this.worldPositionStart),r.visible=this.dragging):r.name==="END"?(r.position.copy(this.worldPosition),r.visible=this.dragging):r.name==="DELTA"?(r.position.copy(this.worldPositionStart),r.quaternion.copy(this.worldQuaternionStart),_t.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),_t.applyQuaternion(this.worldQuaternionStart.clone().invert()),r.scale.copy(_t),r.visible=this.dragging):(r.quaternion.copy(s),this.dragging?r.position.copy(this.worldPositionStart):r.position.copy(this.worldPosition),this.axis&&(r.visible=this.axis.search(r.name)!==-1));continue}r.quaternion.copy(s),this.mode==="translate"||this.mode==="scale"?(r.name==="X"&&Math.abs(Oe.copy(io).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Y"&&Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Z"&&Math.abs(Oe.copy(no).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XY"&&Math.abs(Oe.copy(no).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="YZ"&&Math.abs(Oe.copy(io).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XZ"&&Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1)):this.mode==="rotate"&&(wa.copy(s),Oe.copy(this.eye).applyQuaternion(He.copy(s).invert()),r.name.search("E")!==-1&&r.quaternion.setFromRotationMatrix(Xf.lookAt(this.eye,Yf,nn)),r.name==="X"&&(He.setFromAxisAngle(io,Math.atan2(-Oe.y,Oe.z)),He.multiplyQuaternions(wa,He),r.quaternion.copy(He)),r.name==="Y"&&(He.setFromAxisAngle(nn,Math.atan2(Oe.x,Oe.z)),He.multiplyQuaternions(wa,He),r.quaternion.copy(He)),r.name==="Z"&&(He.setFromAxisAngle(no,Math.atan2(Oe.y,Oe.x)),He.multiplyQuaternions(wa,He),r.quaternion.copy(He))),r.visible=r.visible&&(r.name.indexOf("X")===-1||this.showX),r.visible=r.visible&&(r.name.indexOf("Y")===-1||this.showY),r.visible=r.visible&&(r.name.indexOf("Z")===-1||this.showZ),r.visible=r.visible&&(r.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),r.material._color=r.material._color||r.material.color.clone(),r.material._opacity=r.material._opacity||r.material.opacity,r.material.color.copy(r.material._color),r.material.opacity=r.material._opacity,this.enabled&&this.axis&&(r.name===this.axis||this.axis.split("").some(function(l){return r.name===l}))&&(r.material.color.setHex(16776960),r.material.opacity=1)}super.updateMatrixWorld(e)}}class bN extends x.Mesh{constructor(){super(new x.PlaneGeometry(1e5,1e5,2,2),new x.MeshBasicMaterial({visible:!1,wireframe:!0,side:x.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Ma.copy(io).applyQuaternion(t==="local"?this.worldQuaternion:Ua),Yr.copy(nn).applyQuaternion(t==="local"?this.worldQuaternion:Ua),Xr.copy(no).applyQuaternion(t==="local"?this.worldQuaternion:Ua),Oe.copy(Yr),this.mode){case"translate":case"scale":switch(this.axis){case"X":Oe.copy(this.eye).cross(Ma),Ns.copy(Ma).cross(Oe);break;case"Y":Oe.copy(this.eye).cross(Yr),Ns.copy(Yr).cross(Oe);break;case"Z":Oe.copy(this.eye).cross(Xr),Ns.copy(Xr).cross(Oe);break;case"XY":Ns.copy(Xr);break;case"YZ":Ns.copy(Ma);break;case"XZ":Oe.copy(Xr),Ns.copy(Yr);break;case"XYZ":case"E":Ns.set(0,0,0);break}break;case"rotate":default:Ns.set(0,0,0)}Ns.length()===0?this.quaternion.copy(this.cameraQuaternion):(Zf.lookAt(_t.set(0,0,0),Ns,Oe),this.quaternion.setFromRotationMatrix(Zf)),super.updateMatrixWorld(e)}}class mt extends x.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;three;activeCamera;controls=new Map;visibility=new Map;setApp(e){this.three=e,this.three.addEventListener(de.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();Ls(t)}this.controls=new Map,this.visibility=new Map}add(e){let t=this.controls.get(e);if(t===void 0){const s=document.querySelector(".clickable");t=new dN(this.activeCamera,s),t.getHelper().name=e,t.setSize(.5),t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:mt.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:mt.DRAG_END})}),t.addEventListener("dragging-changed",i=>{tt.instance?.toggleOrbitControls(i.value)})}return t}get(e){return this.controls.get(e)}remove(e){const t=this.get(e);return t===void 0?!1:(t.detach(),t.disconnect(),Ls(t.getHelper()),this.controls.delete(e),!0)}enabled(e){this.controls.forEach(t=>{t.enabled=e})}updateCamera(e,t){this.activeCamera=e,this.controls.forEach(s=>{s.camera!==e&&(s.camera=e,e.getWorldPosition(s.cameraPosition),e.getWorldQuaternion(s.cameraQuaternion)),s.domElement!==t&&(s.disconnect(),s.domElement=t,s.connect(t))})}show(){this.controls.forEach(e=>{const t=e.getHelper(),s=this.visibility.get(t.name);s!==void 0&&(t.visible=s)})}hide(){this.controls.forEach(e=>{const t=e.getHelper();this.visibility.set(t.name,t.visible),t.visible=!1})}setScene=()=>{this.clear()};static get instance(){return mt._instance||(mt._instance=new mt),mt._instance}}const TN=new x.BoxGeometry,oh=new x.Vector2;class ka extends x.Object3D{curve=new x.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new x.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new x.Color(Pi(.5,1,Math.random()),Pi(.5,1,Math.random()),Pi(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new x.LineBasicMaterial({color:s}),this.line=new x.Line(new x.BufferGeometry,this.lineMaterial),this.line.name="line",this.line.visible=!1,this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new x.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new x.Mesh(new x.SphereGeometry(1.5),new x.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new x.Raycaster,this.raycaster.params.Line.threshold=3,this.enable()}enable(){document.addEventListener("pointerdown",this.onMouseClick)}disable(){document.removeEventListener("pointerdown",this.onMouseClick)}dispose=()=>{this._transform&&(this._transform.removeEventListener("objectChange",this.updateSpline),mt.instance.remove(this.name)),this.disable(),this.parentGroup.removeGroup(this.name)};hideTransform=()=>{this._transform?.detach()};exportSpline=()=>{const e=[];this.draggable.children.forEach(t=>{e.push([is(t.position.x,3),is(t.position.y,3),is(t.position.z,3)])}),Jf({name:this.name,points:e,tension:this.tension,closed:this.closed,subdivide:this.subdivide,type:this.curveType}),console.log("Spline copied!")};showPoints=(e=!0)=>{this.draggable.visible=e};addPoints=(e=[])=>{if(e.length>0){const t=e.length-1;for(let s=0;s<t;s++)this.addPoint(e[s],!1);this.addPoint(e[t])}};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,i=new x.Mesh(TN,this.draggedMat);i.name=`point_${s}`,i.position.copy(e),i.scale.setScalar(this._draggableScale),this.draggable.add(i),this._transform?.attach(i);const n=this.points.length>1;return n&&t&&this.updateSpline(),this.line.visible=n,this.updateCurrentPoint(),i};addNextPt=()=>{const e=this.draggable.children.length,t=e>1?this.draggable.children[e-1].position.clone():new x.Vector3,s=this.addPoint(t);this.group.current?.setField("Current Point",s.position)};removePoint=e=>{if(this._transform?.object===e){this._transform?.detach();const t=this.draggable.children[this.draggable.children.length-1];this._transform?.attach(t),this.group.current?.setField("Current Point",t.position)}Ls(e),this.updateSpline()};removePointAt=e=>{const t=this.draggable.children[e];this.removePoint(t)};removeSelectedPt=()=>{this._transform?.object!==void 0&&this.removePoint(this._transform?.object)};updateLastPoint(e){const t=this.draggable.children.length;t>0&&(this.draggable.children[t-1].position.copy(e),this.updateSpline())}updateSpline=()=>{this.points.length<2||(this.curve=new x.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.dispose(),this.line.geometry=new x.BufferGeometry().setFromPoints(this.curve.getPoints(this.subdivide)),this.curvePos.position.copy(this.getPointAt(this._curvePercentage)))};onMouseClick=e=>{if(!tt.instance||!tt.instance.currentWindow||this._transform&&!this._transform.getHelper().visible)return;const s=tt.instance.currentWindow.current.getBoundingClientRect();oh.x=(e.clientX-s.x)/s.width*2-1,oh.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(oh,this.camera);const i=this.raycaster.intersectObjects(this.draggable.children,!1);if(i.length>0){const n=i[0].object;n!==this._transform?.object&&(this._transform?.attach(n),this.group.current?.setField("Current Point",n.position))}};getPointAt(e){return this.curve.points.length>1?this.curve.getPointAt(e):this.curve.points.length===1?this.curve.points[0]:new x.Vector3}getTangentAt(e){return this.curve.getTangentAt(e)}get points(){const e=[];return this.draggable.children.forEach(t=>{e.push(t.position)}),e}get total(){return this.draggable.children.length}get draggableScale(){return this._draggableScale}set draggableScale(e){this._draggableScale=e,this.draggable.children.forEach(t=>t.scale.setScalar(e)),this.curvePos.scale.setScalar(e)}get camera(){return this._camera}set camera(e){this._camera=e,this._transform!==void 0&&(this._transform.camera=e)}get curvePercentage(){return this._curvePercentage}set curvePercentage(e){this._curvePercentage=e,this.curvePos.position.copy(this.getPointAt(e))}updateCurrentPoint(){if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.group.current?.setField("Current Point",e.position)}}onUpdateTransform=()=>{this.updateCurrentPoint(),this.updateSpline()};initDebug(e){const t=this.draggable.children;this.parentGroup=e,this._transform=mt.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),t.length>0&&this._transform.attach(t[t.length-1]),tt.instance?.helpersContainer.add(this._transform.getHelper());const s=t.length>0?t[t.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,expanded:!0,items:[{prop:"Closed",type:"boolean",value:this.closed},{prop:"Visible",type:"boolean",value:this.visible},{prop:"Show Position",type:"boolean",value:this.curvePos.visible},{prop:"Show Points",type:"boolean",value:this.draggable.visible},{prop:"Color",type:"color",value:`#${this.draggedMat.color.getHexString()}`},{prop:"Curve",type:"option",options:[{title:"Catmullrom",value:"catmullrom"},{title:"Centripetal",value:"centripetal"},{title:"Chordal",value:"chordal"}]},{prop:"Draggable Scale",type:"range",min:.01,max:100,step:.01,value:this._draggableScale},{prop:"Subdivide",type:"range",min:1,max:1e3,step:1,value:this.subdivide},{prop:"Tension",type:"range",min:0,max:1,step:.01,value:this.tension},{prop:"New Pt Offset",type:"range",min:0,max:10,value:this.offset},{prop:"Curve At",type:"range",min:0,max:1,step:.01,value:0},{prop:"Toggle Transform",type:"button"},{prop:"Add Point",type:"button"},{prop:"Remove Point",type:"button"},{prop:"Export",type:"button"},{prop:"Delete",type:"button"},{prop:"Current Point",type:"grid3",value:s}],onUpdate:(i,n)=>{switch(i){case"Closed":this.closed=n,this.updateSpline();break;case"Visible":this.visible=n;break;case"Color":this.lineMaterial.color.setStyle(n),this.draggedMat.color.setStyle(n);break;case"Curve":this.curveType=n,this.updateSpline();break;case"Draggable Scale":this.draggableScale=n;break;case"Subdivide":this.subdivide=n,this.updateSpline();break;case"Tension":this.tension=n,this.updateSpline();break;case"New Pt Offset":this.offset=n;break;case"Curve At":this.curvePos.position.copy(this.getPointAt(n));break;case"Show Position":this.curvePos.visible=n;break;case"Show Points":this.draggable.visible=n;break;case"Toggle Transform":this._transform&&(this._transform.getHelper().visible=!this._transform.getHelper().visible);break;case"Add Point":this.addNextPt();break;case"Remove Point":this.removeSelectedPt();break;case"Export":this.exportSpline();break;case"Delete":this.parent.currentSpline=null,Ls(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const r=this._transform?.object;r.name.search("point")>-1&&(r.position.copy(n),this.updateSpline())}break}}}),this.draggable.children.forEach(i=>{this.debugPoint(i)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let Ca=0;class qy extends x.Object3D{defaultScale=10;currentSpline=null;_camera;group=null;three;splineDataText="";constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.three=t,this.three.addEventListener(de.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=Ne.addEditorGroup({title:this.name,items:[{type:"field",prop:"Spline Data",value:"",disabled:!1},{type:"button",prop:"Import Spline"},{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{type:"boolean",prop:"Draw Mode",value:!1},{type:"boolean",prop:"Visible",value:this.visible},{type:"range",prop:"Default Scale",min:0,max:50,step:.01,value:this.defaultScale}],onUpdate:(e,t)=>{switch(e){case"New Spline":this.createSpline();break;case"Spline Data":this.splineDataText=t;break;case"Import Spline":this.createSplineFromJSON(JSON.parse(this.splineDataText));break;case"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break;case"Draw Mode":t?this.enableClickToDraw():this.disableClickToDraw();break}}})}dispose(){this.three.removeEventListener(de.ADD_SPLINE,this.onAddSpline),Ne.removeEditorGroup(this.name)}addSpline(e){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current),this.add(e),this.currentSpline=e}createSpline=(e=[])=>{const t=`Spline ${Ca+1}`,s=new ka(t,this._camera);return s.addPoints(e),this.addSpline(s),Ca++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new x.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=[];e.points.forEach(i=>{t.push(new x.Vector3(i[0],i[1],i[2]))});const s=new ka(e.name,this._camera);return s.closed=e.closed,s.subdivide=e.subdivide,s.tension=e.tension,s.type=e.type,s.addPoints(t),s.updateSpline(),this.addSpline(s),s};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=`Spline ${Ca+1}`,i=[];t.points.forEach(r=>{i.push(new x.Vector3(r[0],r[1],r[2]))});const n=new ka(s,this.camera);n.addPoints(i),this.addSpline(n),Ca++};isMouseDown=!1;enableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.addEventListener("mousedown",this.onClickCanvas),e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("mouseup",this.onMouseUp)})}disableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.removeEventListener("mousedown",this.onClickCanvas),e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("mouseup",this.onMouseUp)})}onClickCanvas=e=>{if(e.button!==0)return;if(this._camera.type!=="OrthographicCamera"){console.warn("Spline Editor - 3D Camera not supported in Draw Mode");return}const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1;if(tt.instance){const a=new x.Raycaster;a.setFromCamera(new x.Vector2(i,n),this._camera);const l=a.intersectObjects(tt.instance.helpersContainer.children,!0);for(let c=0;c<l.length;c++){const h=l[c];if(!(h.object.isLine||h.object.isTransformControlsPlane)&&h.object.isObject3D)return}}this.currentSpline===null&&(this.currentSpline=this.createSpline());const r=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.addPoint(r),this.isMouseDown=!0};onMouseMove=e=>{if(!this.isMouseDown)return;const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1,r=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.updateLastPoint(r)};onMouseUp=()=>{this.isMouseDown=!1};mouseToSplinePos(e,t,s,i){const n=new x.Vector3,r=Math.PI/2,a=this._camera,l=a.zoom,c=a.rotation.x===-6123233995736766e-32&&a.rotation.y===0&&a.rotation.z===0,h=a.rotation.x===-Math.PI&&a.rotation.y===12246467991473532e-32&&a.rotation.z===Math.PI,u=a.rotation.x===-6162975822039155e-48&&a.rotation.y===-r&&a.rotation.z===0,d=a.rotation.x===-6162975822039155e-48&&a.rotation.y===r&&a.rotation.z===0,p=a.rotation.x===-1.5707953264174506&&a.rotation.y===0&&a.rotation.z===0,f=a.rotation.x===1.5707953264174506&&a.rotation.y===0&&a.rotation.z===0;let m=e,y=t;h||d?m*=-1:p&&(y*=-1);const g=s/2/l,_=i/2/l;if(this.currentSpline===null&&(this.currentSpline=this.createSpline()),c||h){const b=m*g+a.position.x,T=y*_+a.position.y;n.set(b,T,0)}else if(u||d){const b=m*g+a.position.z,T=y*_+a.position.y;n.set(0,T,b)}else if(p||f){const b=m*g+a.position.x,T=y*_+a.position.z;n.set(b,0,T)}return n}get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const Qf=["Single","Side by Side","Stacked","Quad"],SN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAC60lEQVRYhe2YT4hNcRTHP48xpmYaNAvRyEQxEhnKQljYsRm9/EmSyJiMFAsMZWNhJYoNIUVJ2VGiyb9ZzIpMpkQSahbGv9GMYWrM+1rc2zjvzvvdd+99rzdvMd+6de75nd+5387vnN/v/G5KEuWMKRNNIB8mCRaKiiL5qQb2ApuBuUAV0Ad0AJeB3sSeJRX6LJbULTf6JTUn9Z+KWMUpPyp/Avoa4CNQZ3Sj/lNpdL/xottR7AjOkHRUUpekN5I6JbVLavDH75lIfZN0UFKTpCWS0pJem/HeJBEMG6yV1ONYtgFJbZJ+GF1jDh+zJb03NuliEuwMkMo4yErS2RA/LcbuYVyCrm1mA7Dal/8Cu4FG4JD/HsTTkCy6a+SVMTPQuc1sBKb78nHghi+/A+YBxwL2lbhRY+ThuARdEVxu5JdGFvACr0otdoZ8Y4+Rn0Sn5sFFsMvI6YB9MzA1YJ8mN8k1wAHzfj4uQVdyrpI0aJL7oqTtkq4FiqPLyCOSbktqlbRL0jlJQ2b8QdwCUZ4qvhRStZL0XFK1pMd57CRvq5mfhKBriRfiFUMY6oD7eOdwPlQAN4G10dfWg+uouwXsiOssAj4AC+JMcEWwvnAuOTEr7gTXPmg34zagOwkbIIOXAo9CbDYBrcBXYN+4UUdy2sRflyS5zVNlfPX7ugpJW5V9nI7mmh+lYU0lCZ2B3TOnAVuAk0BTwC5nuhWro46KauBOQJch5OpRaoIW34GreGf+YZdRqS9NAj4Bp4ClQDvwOWxCqSM4ADQEdKE5XvbXzlITrAVe4TW+M6NMKDXBFLAMuAD0ACfIc7pMZBXXA2cY3/xmodQRHAL2A2+NLtj8ZiEKwUL/z2WMPAJcAVYALWSf8dZuDFGWeBHwKxm3sWYhiGG8Tfo6sA2vSfiSy4GrH3wGrDcfKSSKKf6v1E9yF0XK9Q1XBPuMXMw8HXTonQFwETwNzMFr64v1jzgFHIk9ybHEZYPJo65QlD3Bf2/Q/eaHPiSWAAAAAElFTkSuQmCC",vN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAETklEQVRYhe2YXYhVVRTHf3d0/JhyUrMpFbImM+whSa3Mynww+4AeIgiKoozooQ+KyMyXIAujF6OXqHyI6iEKKYgIP/owsjSFqCkprdDUTEcjbWZ0HHV+Pex1ucfb9Z57Z9REXHA4Z++99l7/s/ZZ/7X2KaiczNLwfwPIk9MA+yunNMAG4DHgV+BvoB3YFff2TPstYEyfrajVroI6Sr1GvahsbJC63HzZq04pmztSvU5tVRuqYRiYg78JeBR4HPg5ntdmxovz9wJfA3uAxuibDLQCA+IqynnAQuBuYCnwMLC1rx48U12U8cZqdWqMDcx4cI16qTpYbVKHqa+ovWUeHKsujn7VL9ULq2HI+wY7gVeBJdGeFu3J4ZUiy/cAXeHRRuAQsC/GC0B3eG4BcH/0tUV7czUAeVsMsBF4Kha9HZgCvAncAuwPnXHA0wFuGLANuDrGuoGDwFxgTqzzQ7RX5FrP2eLsdb76vnogtme6+nE8H1YPlQXHwbi3q9eqn0e7Tb25VrsF68vFY0lb1AGcDTwItGQ8tQM4AIwGmqP/EPAu8A0wElgJfFGzxTo8mKWXu9Rd4ZF96jvqjSbauEC9Sn1O3R463epLaku99voCsFXdkAH3kNpcQW+IiT/bQne3eufxBtioPqP2mKhioXpWzpxb1T8C5Ifh4ZptVoriRmAIKdrI3Lujf3bobAPeJpF0NVkKrAFuI9HTOBIxnxFrF4OgQKKr/dnJlQA+AcwABgOHA4zAamA5cE7orQL+zAEHiWI+A2bFC7aSguheYCgpqAphZz3wSB7AecCICv2TgH8oFRib4gVqka0k0h8CXAxMBW6ooDejFoCvA9OBQUAvKWM0kDz4XUZvNKXtyZMWUl7vBbaQXq457PeEziDgx/KJlQAuIPFdMcEXv5OdYWBP9M8k8VpnDQCvB4aTSrCNJB5cSdrW3tBpIJVnR0qdUTxAfdGUOVTnmwqEanNmqltC/9OgqePKg5eom8PgdvW+oJ9Kupera0O3U50TL3lcAaI+oHaF4R3qa6Z822wq0Saq89T1lmSxOrxeW/Xm4uGkiqQDmECKuKHxHW0HdpMiewSpvGqKeR8Ay0iBsYIjg6261PE2o9Q3Yqv+MqWxO9R1Hl12qs+q49Vlppy82pSr+5xJKsko4AXgHlJ0t5NIeg3wLXAlqZhtIUV8J6nmWwX8QiLjdhL5TwMWkY4R6/rrwYKlMr1Y321QZ/vfwBijPqm+rF4Wc7PjE9QllurGVeoV5gRNHsAm9fnMom3qrKPoTjKdMXaYyrFygEWQ72XWW24qhPu8xcUc2UU6O8wFPjmK7jhgPHAuMJGUGQ6U6WwE5sfzTXGvei7KA9hFOiR9D/wOfFVFt4dS2tpfRe83Ur7/CPiJakfOGgBCypubatArl2r8VfOax/LfzABKtePAzHO/5FgC7KBEzB2kOrDfUm8mOeFySv9+OyFyGmB/5aQH+C9BVKmVCNuMZgAAAABJRU5ErkJggg==",wN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class tt extends W.Component{static instance=null;scene;renderer;currentScene;scenes=new Map;cameras=new Map;controls=new Map;currentCamera;currentWindow;helpersContainer=new x.Group;cameraHelpers=new Map;lightHelpers=new Map;grid=new $y;interactionHelper=new x.AxesHelper(25);currentTransform;splineEditor;depthMaterial=new x.MeshDepthMaterial;normalsMaterial=new x.MeshNormalMaterial;uvMaterial=new jy;wireframeMaterial=new x.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;selectedItem=void 0;debugCamera;raycaster=new x.Raycaster;pointer=new x.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;editorCameras=["Top","Bottom","Left","Right","Front","Back","Orthographic","UI","Debug"];constructor(e){super(e),this.props.three.addEventListener(de.ADD_RENDERER,this.setupRenderer),this.scene=new x.Scene,this.scene.name=this.scene.uuid="",this.canvasRef=W.createRef(),this.containerRef=W.createRef(),this.tlWindow=W.createRef(),this.trWindow=W.createRef(),this.blWindow=W.createRef(),this.brWindow=W.createRef();const t=e.three.name,s=localStorage,i=s.getItem(`${t}_mode`);this.state={mode:i!==null?i:"Single",modeOpen:!1,renderModeOpen:!1,interactionMode:"Orbit",interactionModeOpen:!1,lastUpdate:Date.now()},s.setItem(`${t}_mode`,this.state.mode),s.setItem(`${t}_tlCam`,s.getItem(`${t}_tlCam`)!==null?s.getItem(`${t}_tlCam`):"Debug"),s.setItem(`${t}_trCam`,s.getItem(`${t}_trCam`)!==null?s.getItem(`${t}_trCam`):"Orthographic"),s.setItem(`${t}_blCam`,s.getItem(`${t}_blCam`)!==null?s.getItem(`${t}_blCam`):"Front"),s.setItem(`${t}_brCam`,s.getItem(`${t}_brCam`)!==null?s.getItem(`${t}_brCam`):"Top"),s.setItem(`${t}_tlRender`,s.getItem(`${t}_tlRender`)!==null?s.getItem(`${t}_tlRender`):"Renderer"),s.setItem(`${t}_trRender`,s.getItem(`${t}_trRender`)!==null?s.getItem(`${t}_trRender`):"Renderer"),s.setItem(`${t}_blRender`,s.getItem(`${t}_blRender`)!==null?s.getItem(`${t}_blRender`):"Renderer"),s.setItem(`${t}_brRender`,s.getItem(`${t}_brRender`)!==null?s.getItem(`${t}_brRender`):"Renderer");const n={Vector2:x.Vector2,Vector3:x.Vector3,Vector4:x.Vector4,Quaternion:x.Quaternion,Matrix4:x.Matrix4,Spherical:x.Spherical,Box3:x.Box3,Sphere:x.Sphere,Raycaster:x.Raycaster};Ds.install({THREE:n}),this.setupScene(),this.setupTools();const r=localStorage.getItem(this.expandedCameraVisibility);r!==null&&(this.cameraVisibility=r==="open"),this.saveExpandedCameraVisibility();const a=localStorage.getItem(this.expandedLightVisibility);a!==null&&(this.lightVisibility=a==="open"),this.saveExpandedLightVisibility();const l=localStorage.getItem(this.expandedGridVisibility);l!==null&&(this.gridVisibility=l==="open"),this.grid.visible=this.gridVisibility,this.saveExpandedGridVisibility(),tt.instance=this}componentDidMount(){this.enable(),this.assignControls(),this.resize(),this.play(),mt.instance.setApp(this.props.three),mt.instance.activeCamera=this.debugCamera}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),this.clear(),Ne.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),E.jsxs("div",{className:"multiview",children:[E.jsx("canvas",{ref:this.canvasRef}),E.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&E.jsx(E.Fragment,{children:E.jsx(Qi,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}})}),(this.state.mode==="Side by Side"||this.state.mode==="Stacked")&&E.jsxs(E.Fragment,{children:[E.jsx(Qi,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),E.jsx(Qi,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}})]}),this.state.mode==="Quad"&&E.jsxs(E.Fragment,{children:[E.jsx(Qi,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),E.jsx(Qi,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}}),E.jsx(Qi,{name:"bl",camera:this.blCam,options:e,ref:this.blWindow,onSelectCamera:t=>{this.controls.get(this.blCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.blCam),this.blCam=s,localStorage.setItem(`${this.appID}_blCam`,s.name),this.createControls(s,this.blWindow.current))},onSelectRenderMode:t=>{this.blRender=t,localStorage.setItem(`${this.appID}_blRender`,t)}}),E.jsx(Qi,{name:"br",camera:this.brCam,options:e,ref:this.brWindow,onSelectCamera:t=>{this.controls.get(this.brCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.brCam),this.brCam=s,localStorage.setItem(`${this.appID}_brCam`,s.name),this.createControls(s,this.brWindow.current))},onSelectRenderMode:t=>{this.brRender=t,localStorage.setItem(`${this.appID}_brRender`,t)}})]})]}),E.jsxs("div",{className:"settings",children:[E.jsx(ll,{title:"View",index:Qf.indexOf(this.state.mode),options:Qf,onSelect:t=>{t!==this.state.mode&&(this.killControls(),this.setState({mode:t}),localStorage.setItem(`${this.appID}_mode`,t))},open:this.state.modeOpen,onToggle:t=>{this.setState({modeOpen:t,renderModeOpen:!1,interactionModeOpen:!1})}}),E.jsx(ll,{title:"Interact",index:this.state.interactionMode==="Orbit"?0:1,options:["Orbit Mode","Selection Mode"],onSelect:t=>{this.interactionHelper.visible=t==="Selection Mode",this.setState({interactionMode:this.interactionHelper.visible?"Selection":"Orbit"})},open:this.state.interactionModeOpen,onToggle:t=>{this.setState({modeOpen:!1,renderModeOpen:!1,interactionModeOpen:t})}}),E.jsx(ih,{name:"cameraHelper",icon:SN,selected:this.cameraVisibility,height:24,top:2,onClick:t=>{if(this.cameraVisibility=t,this.saveExpandedCameraVisibility(),this.cameraHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t){const s=this.cameraHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),E.jsx(ih,{name:"lightHelper",icon:vN,selected:this.lightVisibility,height:24,top:4,onClick:t=>{if(this.lightVisibility=t,this.saveExpandedLightVisibility(),this.lightHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t&&this.selectedItem.isLight===!0){const s=this.lightHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),E.jsx(ih,{name:"gridHelper",icon:wN,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.gridVisibility=t,this.saveExpandedGridVisibility(),this.grid.visible=t}})]},this.state.lastUpdate)]})}setupRenderer=e=>{this.renderer&&this.renderer.dispose();const t=this.canvasRef.current;this.props.three.canvas=t;const s=e.value;s.type==="WebGLRenderer"?(this.renderer=new x.WebGLRenderer({canvas:t,stencil:!1}),this.grid.visible=!0):s.type==="WebGPURenderer"&&(this.renderer=new ya({canvas:t,stencil:!1}),this.grid.visible=!1),this.renderer&&(this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setClearColor(0),this.resize(),this.props.three.renderer=this.renderer)};setupScene(){this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.grid.position.y=-1,this.scene.add(this.grid),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(n,r)=>{const a=new x.OrthographicCamera(-100,100,100,-100,0,3e3);return a.name=n,a.position.copy(r),a.lookAt(0,0,0),this.cameras.set(n,a),a},t=1e3;e("Top",new x.Vector3(0,t,0)),e("Bottom",new x.Vector3(0,-t,0)),e("Left",new x.Vector3(-t,0,0)),e("Right",new x.Vector3(t,0,0)),e("Front",new x.Vector3(0,0,t)),e("Back",new x.Vector3(0,0,-t)),e("Orthographic",new x.Vector3(t,t,t)),e("UI",new x.Vector3),this.debugCamera=new x.PerspectiveCamera(60,1,.01,3e3),this.debugCamera.name="Debug",this.debugCamera.position.set(300,300,300),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,i=this.props.three.name;this.tlCam=this.cameras.get(s.getItem(`${i}_tlCam`)),this.trCam=this.cameras.get(s.getItem(`${i}_trCam`)),this.blCam=this.cameras.get(s.getItem(`${i}_blCam`)),this.brCam=this.cameras.get(s.getItem(`${i}_brCam`)),this.tlCam===void 0&&(this.tlCam=this.cameras.get("Debug")),this.trCam===void 0&&(this.trCam=this.cameras.get("Orthographic")),this.blCam===void 0&&(this.blCam=this.cameras.get("Front")),this.brCam===void 0&&(this.brCam=this.cameras.get("Top"))}setupTools(){this.splineEditor=new qy(this.currentCamera,this.three),this.splineEditor.initDebug(),this.helpersContainer.add(this.splineEditor)}play(){this.playing=!0,this.onUpdate()}pause(){this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1}toggleOrbitControls(e){this.controls.forEach(t=>{t.enabled=!e})}clear(){this.three.dispatchEvent({type:de.CLEAR_OBJECT}),Ne.removeAllGroups(),this.clearLightHelpers(),this.clearControls(),this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),mt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=void 0,mt.instance.clear(),this.cameras.forEach(e=>{this.editorCameras.indexOf(e.name)<0&&this.three.dispatchEvent({type:de.REMOVE_CAMERA,value:e})}),this.currentCamera=this.debugCamera,this.currentScene=void 0,this.scenes.forEach(e=>{this.three.dispatchEvent({type:de.REMOVE_SCENE,value:e})}),this.scenes.clear()}update(){this.renderer&&(this.renderer instanceof x.WebGLRenderer?this.renderer?.clear():this.renderer instanceof ya&&this.renderer?.clearAsync()),this.controls.forEach(e=>e.update()),this.cameraHelpers.forEach(e=>e.update()),this.lightHelpers.forEach(e=>{e.update!==void 0&&e.update()}),this.props.onSceneUpdate!==void 0&&this.currentScene!==void 0&&this.props.onSceneUpdate(this.currentScene)}draw(){switch(this.renderer&&(this.renderer instanceof x.WebGLRenderer?this.renderer?.clear():this.renderer instanceof ya&&this.renderer?.clearAsync()),this.state.mode){case"Single":this.drawSingle();break;case"Side by Side":case"Stacked":this.drawDouble();break;case"Quad":this.drawQuad();break}}onUpdate=()=>{this.playing&&(this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate))};enable(){const e=this.containerRef.current;e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("click",this.onClick),window.addEventListener("keydown",this.onKey),window.addEventListener("resize",this.resize),this.three.addEventListener(de.ADD_SCENE,this.addScene),this.three.addEventListener(de.SET_SCENE,this.sceneUpdate),this.three.addEventListener(de.REMOVE_SCENE,this.removeScene),this.three.addEventListener(de.ADD_CAMERA,this.addCamera),this.three.addEventListener(de.REMOVE_CAMERA,this.removeCamera),this.three.addEventListener(de.SET_OBJECT,this.onSetSelectedItem)}disable(){const e=this.containerRef.current;e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("click",this.onClick),window.removeEventListener("keydown",this.onKey),window.removeEventListener("resize",this.resize),this.three.removeEventListener(de.ADD_SCENE,this.addScene),this.three.removeEventListener(de.SET_SCENE,this.sceneUpdate),this.three.removeEventListener(de.ADD_CAMERA,this.addCamera),this.three.removeEventListener(de.REMOVE_CAMERA,this.removeCamera),this.three.removeEventListener(de.SET_OBJECT,this.onSetSelectedItem)}resize=()=>{this.width=window.innerWidth-300,this.height=window.innerHeight,this.renderer?.setSize(this.width,this.height);const e=Math.floor(this.width/2),t=Math.floor(this.height/2);this.props.three.resize(this.width,this.height),this.props.onSceneResize!==void 0&&this.currentScene!==void 0&&this.props.onSceneResize(this.currentScene,this.width,this.height);let s=this.width,i=this.height;switch(this.state.mode){case"Side by Side":s=e,i=this.height;break;case"Stacked":s=this.width,i=t;break;case"Quad":s=e,i=t;break}const n=s/i;this.cameras.forEach(r=>{r instanceof x.OrthographicCamera?(r.left=s/-2,r.right=s/2,r.top=i/2,r.bottom=i/-2,r.name==="UI"&&(r.position.x=this.width/2,r.position.y=this.height/-2,r.position.z=100),r.updateProjectionMatrix()):r instanceof x.PerspectiveCamera&&(r.aspect=n,r.updateProjectionMatrix()),this.cameraHelpers.get(r.name)?.update()})};addScene=e=>{const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;s.visible=!1,this.props.onSceneSet!==void 0&&this.props.onSceneSet(s),this.props.three.scene=s,this.scenes.set(e.value.name,s),this.scene.add(s)}else console.log("Hermes - Scene not found:",e.value.name,this.props.scenes)};sceneUpdate=e=>{this.currentScene!==void 0&&(this.currentScene.visible=!1,this.clearLightHelpers());const t=this.scene.getObjectByName(e.value.name);t!==void 0&&(this.currentScene=t,this.currentScene.visible=!0,this.addLightHelpers(this.currentScene))};removeScene=e=>{const t=e.value.name;this.scenes.delete(t);const s=this.scene.getObjectByName(t);s&&setTimeout(()=>{Ls(s)},100),this.clearLightHelpers()};addCamera=e=>{const t=e.value,s=t.uuid,i=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(i!==void 0){const n=i;this.cameras.set(s,n);const r=new x.CameraHelper(n);r.visible=this.cameraVisibility,this.cameraHelpers.set(s,r),this.helpersContainer.add(r),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const s=e.value.uuid,i=this.cameraHelpers.get(s);i!==void 0&&(this.helpersContainer.remove(i),i.dispose()),this.cameras.delete(s),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new x.Vector2;this.renderer?.getSize(t);const s=Math.min(e.clientX,t.x),i=Math.min(e.clientY,t.y);this.pointer.x=Ji(s,0,t.x,-1,1),this.pointer.y=Ji(i,0,t.y,1,-1);const n=t.x/2,r=t.y/2,a=()=>{s<n?this.pointer.x=Ji(s,0,n,-1,1):this.pointer.x=Ji(s,n,t.x,-1,1)},l=()=>{i<r?this.pointer.y=Ji(i,0,r,1,-1):this.pointer.y=Ji(i,r,t.y,1,-1)};switch(this.state.mode){case"Quad":a(),l();break;case"Side by Side":a();break;case"Stacked":l(),l();break}if(this.updateCamera(s,i,n,r),this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const c=this.raycaster.intersectObjects(this.currentScene.children);c.length>0&&this.interactionHelper.position.copy(c[0].point)};onClick=e=>{if(this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const t=new x.Vector2;if(this.renderer.getSize(t),e.clientX>=t.x)return;this.onMouseMove(e);const s=this.raycaster.intersectObjects(this.currentScene.children);s.length>0&&(this.props.three.getObject(s[0].object.uuid),this.interactionHelper.visible=!1,this.setState({interactionMode:"Orbit",lastUpdate:Date.now()}))};onKey=e=>{if(this.selectedItem!==void 0){if(e.ctrlKey){if(this.currentCamera.name==="UI")return;const t=this.controls.get(this.currentCamera.name);e.key==="0"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof x.Mesh||this.selectedItem instanceof x.SkinnedMesh?(this.selectedItem.geometry.computeBoundingBox(),this.cameraControls.fitToBox(this.selectedItem.geometry.boundingBox,!0)):this.cameraControls.fitToSphere(this.selectedItem,!0),this.updateCameraControls(t,!0)):e.key==="1"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,Math.PI*.5,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="2"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,0,!0),this.cameraControls.moveTo(this.selectedItem.position.x,0,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="3"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI/2,Math.PI/2,!0),this.cameraControls.moveTo(0,this.selectedItem.position.y,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="4"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI,Math.PI/2,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="5"&&(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Ga(45),Ga(45),!0),this.updateCameraControls(t))}else if(this.currentTransform!==void 0)switch(e.key){case"r":this.currentTransform.setMode("rotate");break;case"s":this.currentTransform.setMode("scale");break;case"t":this.currentTransform.setMode("translate");break;case"q":this.currentTransform.setSpace(this.currentTransform.space==="local"?"world":"local");break}}};onSetSelectedItem=e=>{this.selectedItem!==void 0&&this.updateSelectedItemHelper(!1),this.selectedItem=void 0;const t=e.value.uuid;if(this.scenes.forEach(s=>{t.search(s.uuid)>-1&&(this.selectedItem=s.getObjectByProperty("uuid",t))}),this.selectedItem===void 0){console.log(`Hermes - Can't find selected item: ${e.value.uuid}, ${e.value.name}`);return}this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),mt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=mt.instance.add(e.value.name),this.currentTransform.attach(this.selectedItem),this.helpersContainer.add(this.currentTransform.getHelper()),this.currentTransform.addEventListener("objectChange",this.onUpdateTransform),this.updateSelectedItemHelper(!0)};updateSelectedItemHelper(e){if(this.selectedItem!==void 0)if(this.cameraVisibility){if(this.selectedItem.isLight===!0&&!this.lightVisibility){const t=this.lightHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}else{const t=this.cameraHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}onUpdateTransform=()=>{this.selectedItem!==void 0&&(this.props.three.updateObject(this.selectedItem.uuid,"position",this.selectedItem.position),this.props.three.updateObject(this.selectedItem.uuid,"rotation",{x:this.selectedItem.rotation.x,y:this.selectedItem.rotation.y,z:this.selectedItem.rotation.z}),this.props.three.updateObject(this.selectedItem.uuid,"scale",this.selectedItem.scale),Rl.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=e=>{e.traverse(t=>{if(t.type.search("Light")>-1){let s;switch(t.type){case"DirectionalLight":s=new x.DirectionalLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"HemisphereLight":s=new x.HemisphereLightHelper(t,250),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"RectAreaLight":s=new WR(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"PointLight":s=new x.PointLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"SpotLight":s=new x.SpotLightHelper(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break}}})};createControls(e,t){const s=this.controls.get(e.name);if(s!==void 0&&s.dispose(),this.controls.delete(e.name),e.name==="UI")return;const i=new jR(e,t);switch(i.enableDamping=!0,i.dampingFactor=.1,e.name){case"Top":case"Bottom":case"Left":case"Right":case"Front":case"Back":i.enableRotate=!1;break}this.controls.set(e.name,i)}clearCamera(e){const t=this.cameraHelpers.get(e.name);t!==void 0&&(this.helpersContainer.remove(t),t.dispose(),this.cameraHelpers.delete(e.name));const s=this.controls.get(e.name);s!==void 0&&(s.dispose(),this.controls.delete(e.name))}killControls(){this.controls.forEach((e,t)=>{e.dispose();const s=this.cameraHelpers.get(t);s!==void 0&&(this.helpersContainer.remove(s),s.dispose()),this.cameraHelpers.delete(t),this.controls.delete(t)}),this.controls.clear(),this.cameraHelpers.clear()}assignControls(){switch(this.state.mode){case"Single":this.createControls(this.tlCam,this.tlWindow.current);break;case"Side by Side":case"Stacked":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current);break;case"Quad":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current),this.createControls(this.blCam,this.blWindow.current),this.createControls(this.brCam,this.brWindow.current);break}}updateCamera=(e,t,s,i)=>{switch(this.state.mode){case"Quad":t<i?e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam:e<s?this.currentCamera=this.blCam:this.currentCamera=this.brCam;break;case"Side by Side":e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break;case"Single":this.currentCamera=this.tlCam;break;case"Stacked":t<i?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break}this.splineEditor.camera=this.currentCamera,this.raycaster.setFromCamera(this.pointer,this.currentCamera),this.currentCamera===this.tlCam?this.currentWindow=this.tlWindow:this.currentCamera===this.trCam?this.currentWindow=this.trWindow:this.currentCamera===this.blCam?this.currentWindow=this.blWindow:this.currentCamera===this.brCam&&(this.currentWindow=this.brWindow),mt.instance.updateCamera(this.currentCamera,this.currentWindow.current)};updateCameraControls=(e,t=!1)=>{if(this.selectedItem===void 0)return;cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.cameraControls&&(this.cameraControls.smoothTime=.1);const s=.15,i=new x.Clock;i.start(),this.selectedItem.getWorldPosition(e.target0);const n=()=>{const r=i.getDelta();this.cameraControls&&this.cameraControls.update(r),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=or(e.object.zoom,e.zoom0,s),e.object.updateProjectionMatrix(),e.dispatchEvent({type:"change"})),i.getElapsedTime()>=.5?(cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.clearControls()):this.cameraControlsRafID=requestAnimationFrame(n)};n()};clearControls=()=>{this.cameraControls!==void 0&&(this.cameraControls.disconnect(),this.cameraControls.dispose(),this.cameraControls=void 0)};saveExpandedCameraVisibility(){localStorage.setItem(this.expandedCameraVisibility,this.cameraVisibility?"open":"closed")}saveExpandedLightVisibility(){localStorage.setItem(this.expandedLightVisibility,this.lightVisibility?"open":"closed")}saveExpandedGridVisibility(){localStorage.setItem(this.expandedGridVisibility,this.gridVisibility?"open":"closed")}getSceneOverride(e){switch(e){case"Depth":return this.depthMaterial;case"Normals":return this.normalsMaterial;case"Renderer":return null;case"UVs":return this.uvMaterial;case"Wireframe":return this.wireframeMaterial}return null}drawTo(e,t,s,i,n,r){switch(n.name){case"Left":case"Right":this.grid.rotation.z=Math.PI/2;break;case"Front":case"Back":this.grid.rotation.x=Math.PI/2;break}this.scene.overrideMaterial=r,this.renderer&&(this.renderer?.setViewport(e,t,s,i),this.renderer?.setScissor(e,t,s,i),this.renderer instanceof x.WebGLRenderer?this.renderer?.render(this.scene,n):this.renderer instanceof ya&&this.renderer?.renderAsync(this.scene,n)),this.grid.rotation.set(0,0,0)}drawSingle(){const e=this.getSceneOverride(this.tlRender);this.drawTo(0,0,this.width,this.height,this.tlCam,e)}drawDouble=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=Math.floor(this.width/2),i=Math.floor(this.height/2);if(this.state.mode==="Side by Side")this.drawTo(0,0,s,this.height,this.tlCam,e),this.drawTo(s,0,s,this.height,this.trCam,t);else{const n=this.height-i;this.drawTo(0,n,this.width,i,this.tlCam,e),this.drawTo(0,0,this.width,i,this.trCam,t)}};drawQuad=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=this.getSceneOverride(this.blRender),i=this.getSceneOverride(this.brRender),n=Math.floor(this.width/2),r=Math.floor(this.height/2);let a=0,l=0;l=this.height-r,a=0,this.drawTo(a,l,n,r,this.tlCam,e),a=n,this.drawTo(a,l,n,r,this.trCam,t),l=0,a=0,this.scene.overrideMaterial=s,this.drawTo(a,l,n,r,this.blCam,s),a=n,this.drawTo(a,l,n,r,this.brCam,i)};get appID(){return this.props.three.name}get mode(){return this.state.mode}get three(){return this.props.three}get expandedCameraVisibility(){return`${this.appID}_multiviewCameraVisibility`}get expandedLightVisibility(){return`${this.appID}_multiviewLightVisibility`}get expandedGridVisibility(){return`${this.appID}_multiviewGridVisibility`}}class Rl extends W.Component{static instance;matrix=new x.Matrix4;position=new x.Vector3;rotation=new x.Euler;scale=new x.Vector3;open=!1;constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;this.open=s,this.saveExpanded(),this.state={lastUpdated:0,expanded:s},this.matrix.elements=e.object.matrix,e.object.uuid.length>0&&(this.position.setFromMatrixPosition(this.matrix),this.rotation.setFromRotationMatrix(this.matrix),this.scale.setFromMatrixScale(this.matrix)),Rl.instance=this}update(){if(tt.instance){const e=tt.instance.selectedItem;if(e===void 0)return;this.position.x=is(e.position.x,3),this.position.y=is(e.position.y,3),this.position.z=is(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=is(e.scale.x,3),this.scale.y=is(e.scale.y,3),this.scale.z=is(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return E.jsx(hs,{three:this.props.three,title:"Transform",expanded:this.open,items:[{title:"Position",prop:"position",type:"grid3",step:.1,value:this.position,onChange:this.updateTransform},{title:"Rotation",prop:"rotation",type:"euler",value:this.rotation,onChange:this.updateTransform},{title:"Scale",prop:"scale",type:"grid3",value:this.scale,onChange:this.updateTransform},{title:"Visible",prop:"visible",type:"boolean",value:this.props.object.visible,onChange:this.updateTransform}],onToggle:e=>{this.open=e,this.saveExpanded()}},this.state.lastUpdated)}updateTransform=(e,t)=>{const s=e==="rotation"?{x:t._x,y:t._y,z:t._z}:t;this.props.three.updateObject(this.props.object.uuid,e,s);const i=this.props.three.getScene(this.props.object.uuid);if(i){const n=i.getObjectByProperty("uuid",this.props.object.uuid);Ye(n,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.name}_transform`}}function Kf(o){switch(o){case"color":return"Color";case"intensity":return"Intensity";case"decay":return"Decay";case"distance":return"Distance";case"angle":return"Angle";case"penumbra":return"Penumbra";case"groundColor":return"Ground Color";case"width":return"Width";case"height":return"Height"}return o}function MN(o,e){function t(){return`${e.name}_light`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=[];if(o.lightInfo!==void 0)for(const a in o.lightInfo){const l=o.lightInfo[a];l!==void 0&&(l.isColor!==void 0?r.push({title:Kf(a),prop:a,type:"color",value:l,onChange:(c,h)=>{const u=new x.Color(h);e.updateObject(o.uuid,c,u);const d=e.getScene(o.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",o.uuid);Ye(p,c,u)}}}):r.push({title:Kf(a),prop:a,type:typeof l,value:l,step:typeof l=="number"?.01:void 0,onChange:(c,h)=>{e.updateObject(o.uuid,c,h);const u=e.getScene(o.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",o.uuid);Ye(d,c,h)}}}))}return E.jsx(hs,{three:e,title:"Light",items:r,expanded:i,onToggle:a=>{n(a)}})}function CN(o){const e=o.object,t=o.three;function s(){return`${t.name}_animation`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(d){localStorage.setItem(s(),d?"open":"closed")}const a=[],l=[];let c=0;e.animations.forEach(d=>{c=Math.max(c,d.duration),d.duration>0&&l.push({title:d.name,items:[{title:"Duration",type:"number",value:d.duration,disabled:!0},{title:"Blend Mode",type:"option",disabled:!0,options:[{title:"Normal",value:2500},{title:"Additive",value:2501}]}]})}),a.push({title:"Animations",items:l});let h;const u=t.getScene(e.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",e.uuid);if(d!==void 0){const p=d.mixer;if(p!==void 0){const m=[{title:"Time Scale",type:"range",value:p.timeScale,step:.01,min:-1,max:2,onChange:(y,g)=>{p.timeScale=g,t.updateObject(e.uuid,"mixer.timeScale",g)}}];m.push({title:"Stop All",type:"button",onChange:()=>{p.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),a.push({title:"Mixer",items:m}),h=new x.SkeletonHelper(d),tt.instance?.scene.add(h)}}}return W.useEffect(()=>()=>{h!==void 0&&Ls(h)},[]),E.jsx(hs,{three:o.three,title:"Animation",items:a,expanded:n,onToggle:d=>{r(d)}})}const ah={name:"",uuid:"",type:"",visible:!1,matrix:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};function Yy(o){const[e,t]=W.useState(ah);W.useEffect(()=>{function r(l){t(l.value)}function a(){t(ah)}return o.three.addEventListener(de.CLEAR_OBJECT,a),o.three.addEventListener(de.SET_SCENE,a),o.three.addEventListener(de.SET_OBJECT,r),()=>{o.three.removeEventListener(de.CLEAR_OBJECT,a),o.three.removeEventListener(de.SET_SCENE,a),o.three.removeEventListener(de.SET_OBJECT,r)}},[]);const s=e.type.toLowerCase(),i=e.animations.length>0||e.mixer!==void 0,n=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return E.jsx(go,{three:o.three,label:"Inspector",button:e.uuid.length>0?E.jsx("button",{className:"remove",onClick:()=>{mt.instance.remove(e.name),t(ah)}}):void 0,children:E.jsx("div",{id:"Inspector",className:o.class,children:e.uuid.length>0&&E.jsxs(E.Fragment,{children:[E.jsxs(E.Fragment,{children:[E.jsx(Ea,{type:"string",title:"Name",prop:"name",value:e.name,disabled:!0}),E.jsx(Ea,{type:"string",title:"Type",prop:"type",value:e.type,disabled:!0}),E.jsx(Ea,{type:"string",title:"UUID",prop:"uuid",value:e.uuid,disabled:!0})]}),E.jsxs(E.Fragment,{children:[E.jsx(Rl,{object:e,three:o.three}),i?E.jsx(CN,{object:e,three:o.three}):null,s.search("camera")>-1?Qx(e,o.three):null,s.search("light")>-1?MN(e,o.three):null,n?Yx(e,o.three):null]})]})})},"Inspector")}class EN extends W.Component{autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=x.SRGBColorSpace;localClippingEnabled=!1;clearColor=new x.Color(0);clearAlpha=1;toneMapping=x.NoToneMapping;toneMappingExposure=1;type="";constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),tt.instance){const i=tt.instance.renderer;i&&(this.autoClear=i.autoClear,this.autoClearColor=i.autoClearColor,this.autoClearDepth=i.autoClearDepth,this.autoClearStencil=i.autoClearStencil,this.clearAlpha=i.getClearAlpha(),this.toneMapping=i.toneMapping,this.toneMappingExposure=i.toneMappingExposure,i instanceof x.WebGLRenderer&&(this.localClippingEnabled=i.localClippingEnabled,i.getClearColor(this.clearColor)))}this.props.three.addEventListener(de.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.props.three.removeEventListener(de.ADD_RENDERER,this.onAddRenderer)}onAddRenderer=e=>{const t=e.value;if(this.autoClear=t.autoClear,this.autoClearColor=t.autoClearColor,this.autoClearDepth=t.autoClearDepth,this.autoClearStencil=t.autoClearStencil,this.outputColorSpace=t.outputColorSpace,this.localClippingEnabled=t.localClippingEnabled,this.clearAlpha=t.clearAlpha,this.type=t.type,this.toneMapping=t.toneMapping,this.toneMappingExposure=t.toneMappingExposure,this.clearColor.setStyle(t.clearColor,x.LinearSRGBColorSpace),x.ColorManagement.enabled=t.colorManagement,tt.instance){const s=tt.instance.renderer;s&&(s.autoClearColor=this.autoClearColor,s.outputColorSpace=this.outputColorSpace,s.localClippingEnabled=this.localClippingEnabled,s.toneMapping=this.toneMapping,s.toneMappingExposure=this.toneMappingExposure,s.setClearColor(t.clearColor,this.clearAlpha))}this.setState({lastUpdated:Date.now()})};render(){const e=()=>{if(tt.instance){const t=tt.instance.renderer;t&&(t.autoClearColor=this.autoClearColor,t.outputColorSpace=this.outputColorSpace,t.localClippingEnabled=this.localClippingEnabled,t.toneMapping=this.toneMapping,t.toneMappingExposure=this.toneMappingExposure,t.setClearColor(this.clearColor.getStyle(),this.clearAlpha),this.props.three.updateRenderer({autoClear:this.autoClear,autoClearColor:this.autoClearColor,autoClearDepth:this.autoClearDepth,autoClearStencil:this.autoClearStencil,outputColorSpace:this.outputColorSpace,localClippingEnabled:this.localClippingEnabled,clearAlpha:this.clearAlpha,clearColor:this.clearColor.getStyle(),colorManagement:x.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return E.jsx(hs,{three:this.props.three,title:"Renderer",expanded:this.state.expanded,items:[{type:"boolean",title:"Auto Clear",value:this.autoClear,onChange:(t,s)=>{this.autoClear=s}},{type:"boolean",title:"Auto Clear Color",value:this.autoClearColor,onChange:(t,s)=>{this.autoClearColor=s,e()}},{type:"boolean",title:"Auto Clear Depth",value:this.autoClearDepth,onChange:(t,s)=>{this.autoClearDepth=s,e()}},{type:"boolean",title:"Auto Clear Stencil",value:this.autoClearStencil,onChange:(t,s)=>{this.autoClearStencil=s,e()}},{type:"boolean",title:"Local Clipping",value:this.localClippingEnabled,onChange:(t,s)=>{this.localClippingEnabled=s,e()}},{type:"color",title:"Clear Color",value:`#${this.clearColor.getHexString()}`,onChange:(t,s)=>{this.clearColor.setStyle(s),e()}},{type:"range",title:"Clear Alpha",min:0,max:1,step:.01,value:this.clearAlpha,onChange:(t,s)=>{this.clearAlpha=s,e()}},{type:"boolean",title:"Clear Management",value:x.ColorManagement.enabled,onChange:(t,s)=>{x.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:x.NoColorSpace},{title:"SRB Color Space",value:x.SRGBColorSpace},{title:"Linear SRB Color Space",value:x.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:x.NoToneMapping},{title:"Linear ",value:x.LinearToneMapping},{title:"Reinhard",value:x.ReinhardToneMapping},{title:"Cineon ",value:x.CineonToneMapping},{title:"ACES Filmic",value:x.ACESFilmicToneMapping},{title:"AgX",value:x.AgXToneMapping},{title:"Neutral",value:x.NeutralToneMapping},{title:"Custom",value:x.CustomToneMapping}],onChange:(t,s)=>{this.toneMapping=s,e()}},{type:"range",title:"Tone Mapping Exposure",value:this.toneMappingExposure,min:0,max:2,step:.01,onChange:(t,s)=>{this.toneMappingExposure=s,e()}},{type:"string",title:"Type",value:this.type,disabled:!0},{type:"button",title:"Resize Scenes from Source",onChange:()=>{this.props.three.requestSize()}}],onToggle:t=>{this.setState({expanded:t}),this.saveExpanded(t)}},Math.random())}saveExpanded(e){localStorage.setItem(this.expandedName,e?"open":"closed")}get expandedName(){return`${this.props.three.name}_renderer`}}function Xy(o){const[e]=W.useState([]),[t]=W.useState([]),[s,i]=W.useState(0),n=l=>{const c=l.value;e.push(c),t.push(E.jsx(go,{three:o.three,label:`Scene: ${c.name}`,scene:c,open:!0,onRefresh:()=>{o.three.refreshScene(c.name)},children:E.jsx(dh,{child:c,scene:c,three:o.three})},Math.random())),i(Date.now())},r=l=>{const c=l.value;for(let h=0;h<e.length;h++)if(c.uuid===e[h].uuid){e[h]=c,t[h]=E.jsx(go,{three:o.three,label:`Scene: ${c.name}`,scene:c,open:!0,onRefresh:()=>{o.three.refreshScene(c.name)},children:E.jsx(dh,{child:c,scene:c,three:o.three})},Math.random()),i(Date.now());return}},a=l=>{const c=l.value;for(let h=0;h<e.length;h++)if(c.uuid===e[h].uuid){e.splice(h,1),t.splice(h,1),i(Date.now());return}};return W.useEffect(()=>(o.three.addEventListener(de.ADD_SCENE,n),o.three.addEventListener(de.REFRESH_SCENE,r),o.three.addEventListener(de.REMOVE_SCENE,a),()=>{o.three.removeEventListener(de.ADD_SCENE,n),o.three.removeEventListener(de.REFRESH_SCENE,r),o.three.removeEventListener(de.REMOVE_SCENE,a)}),[]),E.jsxs("div",{id:"SidePanel",children:[E.jsx("div",{className:"scenes",children:t},s),E.jsx(Yy,{three:o.three}),E.jsx(EN,{three:o.three}),E.jsx(Ne,{three:o.three})]})}function Zy(o){return E.jsxs("div",{className:"editor",ref:o.ref,style:o.style,children:[E.jsx("div",{className:"header",children:o.header}),o.children,E.jsx("div",{className:"footer",children:o.footer})]})}function AN(o){return E.jsx(Zy,{children:E.jsxs(E.Fragment,{children:[E.jsx(tt,{three:o.three,scenes:o.scenes,onSceneResize:o.onSceneResize,onSceneSet:o.onSceneSet,onSceneUpdate:o.onSceneUpdate}),E.jsx(Xy,{three:o.three})]})})}exports.Accordion=go;exports.Application=ix;exports.BaseRemote=Xh;exports.ChildObject=Qh;exports.ContainerObject=dh;exports.Draggable=um;exports.DraggableItem=hm;exports.Dropdown=dm;exports.DropdownItem=pm;exports.Editor=Zy;exports.ElementProxy=tx;exports.ElementProxyReceiver=lm;exports.ExportTexture=Ni;exports.InfiniteGridHelper=$y;exports.InfiniteGridMaterial=Wy;exports.Inspector=Yy;exports.MultiView=tt;exports.NavButton=Zh;exports.ProxyManager=sx;exports.RemoteTheatre=ox;exports.RemoteThree=dx;exports.SidePanel=Xy;exports.Spline=ka;exports.SplineEditor=qy;exports.ThreeEditor=AN;exports.Transform=mt;exports.UVMaterial=jy;exports.WebworkerEventHandlers=J0;exports.animateObjectMaterial=V0;exports.animateObjectTransform=k0;exports.applyObjectMaterial=om;exports.capitalize=mo;exports.clamp=Si;exports.clearComposerGroups=W0;exports.colorToHex=lh;exports.copyToClipboard=Jf;exports.cubicBezier=I0;exports.customizeTheatreElements=U0;exports.damp=N0;exports.defaultTheatreCallback=S0;exports.detectMaxFrameRate=sm;exports.detectSettings=im;exports.dispose=Ls;exports.disposeMaterial=qh;exports.disposeTexture=ch;exports.distance=R0;exports.generateCubemap=$0;exports.getObjectMaterialObject=rm;exports.getObjectMaterialProps=nm;exports.hierarchyUUID=Va;exports.inspectComposer=H0;exports.inspectComposerPass=am;exports.isColor=em;exports.map=A0;exports.mix=or;exports.noop=fo;exports.normalize=za;exports.parseModelLite=G0;exports.randomID=ht;exports.resetThreeObjects=hh;exports.rgbaToHex=L0;exports.round=is;exports.roundTo=P0;
|
|
600
|
+
}`;class Zy extends y.ShaderMaterial{constructor(){super({defines:{USE_UV:""},vertexShader:ON,fragmentShader:BN})}}const Qi=new y.Raycaster,_t=new y.Vector3,bi=new y.Vector3,He=new y.Quaternion,qf={X:new y.Vector3(1,0,0),Y:new y.Vector3(0,1,0),Z:new y.Vector3(0,0,1)},ah={type:"change"},Yf={type:"mouseDown",mode:null},Xf={type:"mouseUp",mode:null},Zf={type:"objectChange"};class IN extends y.Controls{constructor(e,t=null){super(void 0,t);const s=new VN(this);this._root=s;const i=new HN;this._gizmo=i,s.add(i);const n=new WN;this._plane=n,s.add(n);const r=this;function a(b,T){let S=T;Object.defineProperty(r,b,{get:function(){return S!==void 0?S:T},set:function(C){S!==C&&(S=C,n[b]=C,i[b]=C,r.dispatchEvent({type:b+"-changed",value:C}),r.dispatchEvent(ah))}}),r[b]=T,n[b]=T,i[b]=T}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new y.Vector3,c=new y.Vector3,h=new y.Quaternion,u=new y.Quaternion,d=new y.Vector3,p=new y.Quaternion,f=new y.Vector3,m=new y.Vector3,x=new y.Vector3,g=0,_=new y.Vector3;a("worldPosition",l),a("worldPositionStart",c),a("worldQuaternion",h),a("worldQuaternionStart",u),a("cameraPosition",d),a("cameraQuaternion",p),a("pointStart",f),a("pointEnd",m),a("rotationAxis",x),a("rotationAngle",g),a("eye",_),this._offset=new y.Vector3,this._startNorm=new y.Vector3,this._endNorm=new y.Vector3,this._cameraScale=new y.Vector3,this._parentPosition=new y.Vector3,this._parentQuaternion=new y.Quaternion,this._parentQuaternionInv=new y.Quaternion,this._parentScale=new y.Vector3,this._worldScaleStart=new y.Vector3,this._worldQuaternionInv=new y.Quaternion,this._worldScale=new y.Vector3,this._positionStart=new y.Vector3,this._quaternionStart=new y.Quaternion,this._scaleStart=new y.Vector3,this._getPointer=LN.bind(this),this._onPointerDown=kN.bind(this),this._onPointerHover=UN.bind(this),this._onPointerMove=zN.bind(this),this._onPointerUp=GN.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&Qi.setFromCamera(e,this.camera);const t=lh(this._gizmo.picker[this.mode],Qi);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&Qi.setFromCamera(e,this.camera);const t=lh(this._plane,Qi,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,Yf.mode=this.mode,this.dispatchEvent(Yf)}}pointerMove(e){const t=this.axis,s=this.mode,i=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),i===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&Qi.setFromCamera(e,this.camera);const r=lh(this._plane,Qi,!0);if(r){if(this.pointEnd.copy(r.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(i.position.applyQuaternion(He.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),n==="world"&&(i.parent&&i.position.add(_t.setFromMatrixPosition(i.parent.matrixWorld)),t.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(_t.setFromMatrixPosition(i.parent.matrixWorld)))),i.position.x=Math.max(this.minX,Math.min(this.maxX,i.position.x)),i.position.y=Math.max(this.minY,Math.min(this.maxY,i.position.y)),i.position.z=Math.max(this.minZ,Math.min(this.maxZ,i.position.z));else if(s==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),bi.set(a,a,a)}else _t.copy(this.pointStart),bi.copy(this.pointEnd),_t.applyQuaternion(this._worldQuaternionInv),bi.applyQuaternion(this._worldQuaternionInv),bi.divide(_t),t.search("X")===-1&&(bi.x=1),t.search("Y")===-1&&(bi.y=1),t.search("Z")===-1&&(bi.z=1);i.scale.copy(this._scaleStart).multiply(bi),this.scaleSnap&&(t.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(_t.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(_t.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(qf[t]),_t.copy(qf[t]),n==="local"&&_t.applyQuaternion(this.worldQuaternion),_t.cross(this.eye),_t.length()===0?l=!0:this.rotationAngle=this._offset.dot(_t.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(He.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(He.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(ah),this.dispatchEvent(Zf)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(Xf.mode=this.mode,this.dispatchEvent(Xf)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(ah),this.dispatchEvent(Zf),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Qi}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function LN(o){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:o.button};{const e=this.domElement.getBoundingClientRect();return{x:(o.clientX-e.left)/e.width*2-1,y:-(o.clientY-e.top)/e.height*2+1,button:o.button}}}function UN(o){if(this.enabled)switch(o.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(o));break}}function kN(o){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(o)),this.pointerDown(this._getPointer(o)))}function zN(o){this.enabled&&this.pointerMove(this._getPointer(o))}function GN(o){this.enabled&&(this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(o)))}function lh(o,e,t){const s=e.intersectObject(o,!0);for(let i=0;i<s.length;i++)if(s[i].object.visible||t)return s[i];return!1}const wa=new y.Euler,Oe=new y.Vector3(0,1,0),Kf=new y.Vector3(0,0,0),Qf=new y.Matrix4,Ma=new y.Quaternion,za=new y.Quaternion,Ns=new y.Vector3,Jf=new y.Matrix4,ro=new y.Vector3(1,0,0),nn=new y.Vector3(0,1,0),oo=new y.Vector3(0,0,1),Ca=new y.Vector3,Zr=new y.Vector3,Kr=new y.Vector3;class VN extends y.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;t.object!==void 0&&(t.object.updateMatrixWorld(),t.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class HN extends y.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new y.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new y.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const i=t.clone();i.opacity=.5;const n=e.clone();n.color.setHex(16711680);const r=e.clone();r.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const u=e.clone();u.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const m=new y.CylinderGeometry(0,.04,.1,12);m.translate(0,.05,0);const x=new y.BoxGeometry(.08,.08,.08);x.translate(0,.04,0);const g=new y.BufferGeometry;g.setAttribute("position",new y.Float32BufferAttribute([0,0,0,1,0,0],3));const _=new y.CylinderGeometry(.0075,.0075,.5,3);_.translate(0,.25,0);function b(Z,we){const de=new y.TorusGeometry(Z,.0075,3,64,we*Math.PI*2);return de.rotateY(Math.PI/2),de.rotateX(Math.PI/2),de}function T(){const Z=new y.BufferGeometry;return Z.setAttribute("position",new y.Float32BufferAttribute([0,0,0,1,1,1],3)),Z}const S={X:[[new y.Mesh(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new y.Mesh(m,n),[-.5,0,0],[0,0,Math.PI/2]],[new y.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new y.Mesh(m,r),[0,.5,0]],[new y.Mesh(m,r),[0,-.5,0],[Math.PI,0,0]],[new y.Mesh(_,r)]],Z:[[new y.Mesh(m,a),[0,0,.5],[Math.PI/2,0,0]],[new y.Mesh(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new y.Mesh(_,a),null,[Math.PI/2,0,0]]],XYZ:[[new y.Mesh(new y.OctahedronGeometry(.1,0),u.clone()),[0,0,0]]],XY:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),h.clone()),[.15,.15,0]]],YZ:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},C={X:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new y.Mesh(new y.OctahedronGeometry(.2,0),s)]],XY:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},w={START:[[new y.Mesh(new y.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],END:[[new y.Mesh(new y.OctahedronGeometry(.01,2),i),null,null,null,"helper"]],DELTA:[[new y.Line(T(),i),null,null,null,"helper"]],X:[[new y.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new y.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new y.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},R={XYZE:[[new y.Mesh(b(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new y.Mesh(b(.5,.5),n)]],Y:[[new y.Mesh(b(.5,.5),r),null,[0,0,-Math.PI/2]]],Z:[[new y.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new y.Mesh(b(.75,1),d),null,[0,Math.PI/2,0]]]},P={AXIS:[[new y.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},z={XYZE:[[new y.Mesh(new y.SphereGeometry(.25,10,8),s)]],X:[[new y.Mesh(new y.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new y.Mesh(new y.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new y.Mesh(new y.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new y.Mesh(new y.TorusGeometry(.75,.1,2,24),s)]]},$={X:[[new y.Mesh(x,n),[.5,0,0],[0,0,-Math.PI/2]],[new y.Mesh(_,n),[0,0,0],[0,0,-Math.PI/2]],[new y.Mesh(x,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new y.Mesh(x,r),[0,.5,0]],[new y.Mesh(_,r)],[new y.Mesh(x,r),[0,-.5,0],[0,0,Math.PI]]],Z:[[new y.Mesh(x,a),[0,0,.5],[Math.PI/2,0,0]],[new y.Mesh(_,a),[0,0,0],[Math.PI/2,0,0]],[new y.Mesh(x,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new y.Mesh(new y.BoxGeometry(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new y.Mesh(new y.BoxGeometry(.1,.1,.1),u.clone())]]},q={X:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new y.Mesh(new y.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new y.Mesh(new y.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new y.Mesh(new y.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},j={X:[[new y.Line(g,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new y.Line(g,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new y.Line(g,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function X(Z){const we=new y.Object3D;for(const de in Z)for(let ye=Z[de].length;ye--;){const se=Z[de][ye][0].clone(),Me=Z[de][ye][1],ze=Z[de][ye][2],ot=Z[de][ye][3],be=Z[de][ye][4];se.name=de,se.tag=be,Me&&se.position.set(Me[0],Me[1],Me[2]),ze&&se.rotation.set(ze[0],ze[1],ze[2]),ot&&se.scale.set(ot[0],ot[1],ot[2]),se.updateMatrix();const at=se.geometry.clone();at.applyMatrix4(se.matrix),se.geometry=at,se.renderOrder=1/0,se.position.set(0,0,0),se.rotation.set(0,0,0),se.scale.set(1,1,1),we.add(se)}return we}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=X(S)),this.add(this.gizmo.rotate=X(R)),this.add(this.gizmo.scale=X($)),this.add(this.picker.translate=X(C)),this.add(this.picker.rotate=X(z)),this.add(this.picker.scale=X(q)),this.add(this.helper.translate=X(w)),this.add(this.helper.rotate=X(P)),this.add(this.helper.scale=X(j)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const s=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:za;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let n=0;n<i.length;n++){const r=i[n];r.visible=!0,r.rotation.set(0,0,0),r.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),r.scale.set(1,1,1).multiplyScalar(a*this.size/4),r.tag==="helper"){r.visible=!1,r.name==="AXIS"?(r.visible=!!this.axis,this.axis==="X"&&(He.setFromEuler(wa.set(0,0,0)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(ro).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Y"&&(He.setFromEuler(wa.set(0,0,Math.PI/2)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="Z"&&(He.setFromEuler(wa.set(0,Math.PI/2,0)),r.quaternion.copy(s).multiply(He),Math.abs(Oe.copy(oo).applyQuaternion(s).dot(this.eye))>.9&&(r.visible=!1)),this.axis==="XYZE"&&(He.setFromEuler(wa.set(0,Math.PI/2,0)),Oe.copy(this.rotationAxis),r.quaternion.setFromRotationMatrix(Qf.lookAt(Kf,Oe,nn)),r.quaternion.multiply(He),r.visible=this.dragging),this.axis==="E"&&(r.visible=!1)):r.name==="START"?(r.position.copy(this.worldPositionStart),r.visible=this.dragging):r.name==="END"?(r.position.copy(this.worldPosition),r.visible=this.dragging):r.name==="DELTA"?(r.position.copy(this.worldPositionStart),r.quaternion.copy(this.worldQuaternionStart),_t.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),_t.applyQuaternion(this.worldQuaternionStart.clone().invert()),r.scale.copy(_t),r.visible=this.dragging):(r.quaternion.copy(s),this.dragging?r.position.copy(this.worldPositionStart):r.position.copy(this.worldPosition),this.axis&&(r.visible=this.axis.search(r.name)!==-1));continue}r.quaternion.copy(s),this.mode==="translate"||this.mode==="scale"?(r.name==="X"&&Math.abs(Oe.copy(ro).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Y"&&Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="Z"&&Math.abs(Oe.copy(oo).applyQuaternion(s).dot(this.eye))>.99&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XY"&&Math.abs(Oe.copy(oo).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="YZ"&&Math.abs(Oe.copy(ro).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1),r.name==="XZ"&&Math.abs(Oe.copy(nn).applyQuaternion(s).dot(this.eye))<.2&&(r.scale.set(1e-10,1e-10,1e-10),r.visible=!1)):this.mode==="rotate"&&(Ma.copy(s),Oe.copy(this.eye).applyQuaternion(He.copy(s).invert()),r.name.search("E")!==-1&&r.quaternion.setFromRotationMatrix(Qf.lookAt(this.eye,Kf,nn)),r.name==="X"&&(He.setFromAxisAngle(ro,Math.atan2(-Oe.y,Oe.z)),He.multiplyQuaternions(Ma,He),r.quaternion.copy(He)),r.name==="Y"&&(He.setFromAxisAngle(nn,Math.atan2(Oe.x,Oe.z)),He.multiplyQuaternions(Ma,He),r.quaternion.copy(He)),r.name==="Z"&&(He.setFromAxisAngle(oo,Math.atan2(Oe.y,Oe.x)),He.multiplyQuaternions(Ma,He),r.quaternion.copy(He))),r.visible=r.visible&&(r.name.indexOf("X")===-1||this.showX),r.visible=r.visible&&(r.name.indexOf("Y")===-1||this.showY),r.visible=r.visible&&(r.name.indexOf("Z")===-1||this.showZ),r.visible=r.visible&&(r.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),r.material._color=r.material._color||r.material.color.clone(),r.material._opacity=r.material._opacity||r.material.opacity,r.material.color.copy(r.material._color),r.material.opacity=r.material._opacity,this.enabled&&this.axis&&(r.name===this.axis||this.axis.split("").some(function(l){return r.name===l}))&&(r.material.color.setHex(16776960),r.material.opacity=1)}super.updateMatrixWorld(e)}}class WN extends y.Mesh{constructor(){super(new y.PlaneGeometry(1e5,1e5,2,2),new y.MeshBasicMaterial({visible:!1,wireframe:!0,side:y.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Ca.copy(ro).applyQuaternion(t==="local"?this.worldQuaternion:za),Zr.copy(nn).applyQuaternion(t==="local"?this.worldQuaternion:za),Kr.copy(oo).applyQuaternion(t==="local"?this.worldQuaternion:za),Oe.copy(Zr),this.mode){case"translate":case"scale":switch(this.axis){case"X":Oe.copy(this.eye).cross(Ca),Ns.copy(Ca).cross(Oe);break;case"Y":Oe.copy(this.eye).cross(Zr),Ns.copy(Zr).cross(Oe);break;case"Z":Oe.copy(this.eye).cross(Kr),Ns.copy(Kr).cross(Oe);break;case"XY":Ns.copy(Kr);break;case"YZ":Ns.copy(Ca);break;case"XZ":Oe.copy(Kr),Ns.copy(Zr);break;case"XYZ":case"E":Ns.set(0,0,0);break}break;case"rotate":default:Ns.set(0,0,0)}Ns.length()===0?this.quaternion.copy(this.cameraQuaternion):(Jf.lookAt(_t.set(0,0,0),Ns,Oe),this.quaternion.setFromRotationMatrix(Jf)),super.updateMatrixWorld(e)}}class mt extends y.EventDispatcher{static DRAG_START="Transform::dragStart";static DRAG_END="Transform::dragEnd";static _instance;three;activeCamera;controls=new Map;visibility=new Map;setApp(e){this.three=e,this.three.addEventListener(ce.SET_SCENE,this.setScene)}clear(){for(const e of this.controls.values()){e.detach(),e.disconnect();const t=e.getHelper();Ls(t)}this.controls=new Map,this.visibility=new Map}add(e){let t=this.controls.get(e);if(t===void 0){const s=document.querySelector(".clickable");t=new IN(this.activeCamera,s),t.getHelper().name=e,t.setSize(.5),t.setSpace("local"),this.controls.set(e,t),this.visibility.set(e,!0),t.addEventListener("mouseDown",()=>{this.dispatchEvent({type:mt.DRAG_START})}),t.addEventListener("mouseUp",()=>{this.dispatchEvent({type:mt.DRAG_END})}),t.addEventListener("dragging-changed",i=>{tt.instance?.toggleOrbitControls(i.value)})}return t}get(e){return this.controls.get(e)}remove(e){const t=this.get(e);return t===void 0?!1:(t.detach(),t.disconnect(),Ls(t.getHelper()),this.controls.delete(e),!0)}enabled(e){this.controls.forEach(t=>{t.enabled=e})}updateCamera(e,t){this.activeCamera=e,this.controls.forEach(s=>{s.camera!==e&&(s.camera=e,e.getWorldPosition(s.cameraPosition),e.getWorldQuaternion(s.cameraQuaternion)),s.domElement!==t&&(s.disconnect(),s.domElement=t,s.connect(t))})}show(){this.controls.forEach(e=>{const t=e.getHelper(),s=this.visibility.get(t.name);s!==void 0&&(t.visible=s)})}hide(){this.controls.forEach(e=>{const t=e.getHelper();this.visibility.set(t.name,t.visible),t.visible=!1})}setScene=()=>{this.clear()};static get instance(){return mt._instance||(mt._instance=new mt),mt._instance}}const $N=new y.BoxGeometry,ch=new y.Vector2;class Ga extends y.Object3D{curve=new y.CatmullRomCurve3;line;draggable;curvePos;tension=.5;closed=!1;subdivide=50;curveType;offset=1;lineMaterial;_camera;_curvePercentage=0;_draggableScale=10;_transform;raycaster;draggedMat=new y.MeshBasicMaterial;parentGroup;group;constructor(e,t){const s=new y.Color(Pi(.5,1,Math.random()),Pi(.5,1,Math.random()),Pi(.5,1,Math.random()));super(),this.name=e,this.lineMaterial=new y.LineBasicMaterial({color:s}),this.line=new y.Line(new y.BufferGeometry,this.lineMaterial),this.line.name="line",this.line.visible=!1,this.add(this.line),this._camera=t,this.curveType="catmullrom",this.draggedMat.color=s,this.draggable=new y.Object3D,this.draggable.name="draggablePoints",this.add(this.draggable),this.curvePos=new y.Mesh(new y.SphereGeometry(1.5),new y.MeshBasicMaterial({color:s})),this.curvePos.name="curvePos",this.curvePos.scale.setScalar(this._draggableScale),this.curvePos.visible=!1,this.add(this.curvePos),this.raycaster=new y.Raycaster,this.raycaster.params.Line.threshold=3,this.enable()}enable(){document.addEventListener("pointerdown",this.onMouseClick)}disable(){document.removeEventListener("pointerdown",this.onMouseClick)}dispose=()=>{this._transform&&(this._transform.removeEventListener("objectChange",this.updateSpline),mt.instance.remove(this.name)),this.disable(),this.parentGroup.removeGroup(this.name)};hideTransform=()=>{this._transform?.detach()};exportSpline=()=>{const e=[];this.draggable.children.forEach(t=>{e.push([is(t.position.x,3),is(t.position.y,3),is(t.position.z,3)])}),sm({name:this.name,points:e,tension:this.tension,closed:this.closed,subdivide:this.subdivide,type:this.curveType}),console.log("Spline copied!")};showPoints=(e=!0)=>{this.draggable.visible=e};addPoints=(e=[])=>{if(e.length>0){const t=e.length-1;for(let s=0;s<t;s++)this.addPoint(e[s],!1);this.addPoint(e[t])}};addPoint=(e,t=!0)=>{const s=this.draggable.children.length,i=new y.Mesh($N,this.draggedMat);i.name=`point_${s}`,i.position.copy(e),i.scale.setScalar(this._draggableScale),this.draggable.add(i),this._transform?.attach(i);const n=this.points.length>1;return n&&t&&this.updateSpline(),this.line.visible=n,this.updateCurrentPoint(),i};addNextPt=()=>{const e=this.draggable.children.length,t=e>1?this.draggable.children[e-1].position.clone():new y.Vector3,s=this.addPoint(t);this.group.current?.setField("Current Point",s.position)};removePoint=e=>{if(this._transform?.object===e){this._transform?.detach();const t=this.draggable.children[this.draggable.children.length-1];this._transform?.attach(t),this.group.current?.setField("Current Point",t.position)}Ls(e),this.updateSpline()};removePointAt=e=>{const t=this.draggable.children[e];this.removePoint(t)};removeSelectedPt=()=>{this._transform?.object!==void 0&&this.removePoint(this._transform?.object)};updateLastPoint(e){const t=this.draggable.children.length;t>0&&(this.draggable.children[t-1].position.copy(e),this.updateSpline())}updateSpline=()=>{this.points.length<2||(this.curve=new y.CatmullRomCurve3(this.points,this.closed,this.curveType,this.tension),this.line.geometry.dispose(),this.line.geometry=new y.BufferGeometry().setFromPoints(this.curve.getPoints(this.subdivide)),this.curvePos.position.copy(this.getPointAt(this._curvePercentage)))};onMouseClick=e=>{if(!tt.instance||!tt.instance.currentWindow||this._transform&&!this._transform.getHelper().visible)return;const s=tt.instance.currentWindow.current.getBoundingClientRect();ch.x=(e.clientX-s.x)/s.width*2-1,ch.y=-((e.clientY-s.y)/s.height)*2+1,this.raycaster.setFromCamera(ch,this.camera);const i=this.raycaster.intersectObjects(this.draggable.children,!1);if(i.length>0){const n=i[0].object;n!==this._transform?.object&&(this._transform?.attach(n),this.group.current?.setField("Current Point",n.position))}};getPointAt(e){return this.curve.points.length>1?this.curve.getPointAt(e):this.curve.points.length===1?this.curve.points[0]:new y.Vector3}getTangentAt(e){return this.curve.getTangentAt(e)}get points(){const e=[];return this.draggable.children.forEach(t=>{e.push(t.position)}),e}get total(){return this.draggable.children.length}get draggableScale(){return this._draggableScale}set draggableScale(e){this._draggableScale=e,this.draggable.children.forEach(t=>t.scale.setScalar(e)),this.curvePos.scale.setScalar(e)}get camera(){return this._camera}set camera(e){this._camera=e,this._transform!==void 0&&(this._transform.camera=e)}get curvePercentage(){return this._curvePercentage}set curvePercentage(e){this._curvePercentage=e,this.curvePos.position.copy(this.getPointAt(e))}updateCurrentPoint(){if(this._transform?.object&&this.group){const e=this._transform?.object;e.name.search("point")>-1&&this.group.current?.setField("Current Point",e.position)}}onUpdateTransform=()=>{this.updateCurrentPoint(),this.updateSpline()};initDebug(e){const t=this.draggable.children;this.parentGroup=e,this._transform=mt.instance.add(this.name),this._transform.camera=this._camera,this._transform.addEventListener("objectChange",this.onUpdateTransform),t.length>0&&this._transform.attach(t[t.length-1]),tt.instance?.helpersContainer.add(this._transform.getHelper());const s=t.length>0?t[t.length-1].position:{x:0,y:0,z:0};this.group=e.addGroup({title:this.name,expanded:!0,items:[{prop:"Closed",type:"boolean",value:this.closed},{prop:"Visible",type:"boolean",value:this.visible},{prop:"Show Position",type:"boolean",value:this.curvePos.visible},{prop:"Show Points",type:"boolean",value:this.draggable.visible},{prop:"Color",type:"color",value:`#${this.draggedMat.color.getHexString()}`},{prop:"Curve",type:"option",options:[{title:"Catmullrom",value:"catmullrom"},{title:"Centripetal",value:"centripetal"},{title:"Chordal",value:"chordal"}]},{prop:"Draggable Scale",type:"range",min:.01,max:100,step:.01,value:this._draggableScale},{prop:"Subdivide",type:"range",min:1,max:1e3,step:1,value:this.subdivide},{prop:"Tension",type:"range",min:0,max:1,step:.01,value:this.tension},{prop:"New Pt Offset",type:"range",min:0,max:10,value:this.offset},{prop:"Curve At",type:"range",min:0,max:1,step:.01,value:0},{prop:"Toggle Transform",type:"button"},{prop:"Add Point",type:"button"},{prop:"Remove Point",type:"button"},{prop:"Export",type:"button"},{prop:"Delete",type:"button"},{prop:"Current Point",type:"grid3",value:s}],onUpdate:(i,n)=>{switch(i){case"Closed":this.closed=n,this.updateSpline();break;case"Visible":this.visible=n;break;case"Color":this.lineMaterial.color.setStyle(n),this.draggedMat.color.setStyle(n);break;case"Curve":this.curveType=n,this.updateSpline();break;case"Draggable Scale":this.draggableScale=n;break;case"Subdivide":this.subdivide=n,this.updateSpline();break;case"Tension":this.tension=n,this.updateSpline();break;case"New Pt Offset":this.offset=n;break;case"Curve At":this.curvePos.position.copy(this.getPointAt(n));break;case"Show Position":this.curvePos.visible=n;break;case"Show Points":this.draggable.visible=n;break;case"Toggle Transform":this._transform&&(this._transform.getHelper().visible=!this._transform.getHelper().visible);break;case"Add Point":this.addNextPt();break;case"Remove Point":this.removeSelectedPt();break;case"Export":this.exportSpline();break;case"Delete":this.parent.currentSpline=null,Ls(this);break;case"Current Point":if(this.group.current&&this._transform?.object){const r=this._transform?.object;r.name.search("point")>-1&&(r.position.copy(n),this.updateSpline())}break}}}),this.draggable.children.forEach(i=>{this.debugPoint(i)})}debugPoint=e=>{e.name,e.visible=this.draggable.visible}}let Ea=0;class Ky extends y.Object3D{defaultScale=10;currentSpline=null;_camera;group=null;three;splineDataText="";constructor(e,t){super(),this.name="Spline Editor",this._camera=e,this.three=t,this.three.addEventListener(ce.ADD_SPLINE,this.onAddSpline)}initDebug(){this.group=Ne.addEditorGroup({title:this.name,items:[{type:"field",prop:"Spline Data",value:"",disabled:!1},{type:"button",prop:"Import Spline"},{type:"button",prop:"New Spline"},{type:"boolean",prop:"Show Points",value:!0},{type:"boolean",prop:"Draw Mode",value:!1},{type:"boolean",prop:"Visible",value:this.visible},{type:"range",prop:"Default Scale",min:0,max:50,step:.01,value:this.defaultScale}],onUpdate:(e,t)=>{switch(e){case"New Spline":this.createSpline();break;case"Spline Data":this.splineDataText=t;break;case"Import Spline":this.createSplineFromJSON(JSON.parse(this.splineDataText));break;case"Show Points":this.showPoints(t);break;case"Visible":this.visible=t;break;case"Default Scale":this.defaultScale=t;break;case"Draw Mode":t?this.enableClickToDraw():this.disableClickToDraw();break}}})}dispose(){this.three.removeEventListener(ce.ADD_SPLINE,this.onAddSpline),Ne.removeEditorGroup(this.name)}addSpline(e){e.draggableScale=this.defaultScale,e.hideTransform(),this.group?.current!==null&&e.initDebug(this.group.current),this.add(e),this.currentSpline=e}createSpline=(e=[])=>{const t=`Spline ${Ea+1}`,s=new Ga(t,this._camera);return s.addPoints(e),this.addSpline(s),Ea++,s};createSplineFromArray=e=>{const t=[];return e.forEach(s=>{t.push(new y.Vector3(s[0],s[1],s[2]))}),this.createSpline(t)};createSplineFromCatmullRom=e=>this.createSpline(e.points);createSplineFromJSON=e=>{const t=[];e.points.forEach(i=>{t.push(new y.Vector3(i[0],i[1],i[2]))});const s=new Ga(e.name,this._camera);return s.closed=e.closed,s.subdivide=e.subdivide,s.tension=e.tension,s.type=e.type,s.addPoints(t),s.updateSpline(),this.addSpline(s),s};showPoints=(e=!0)=>{this.children.forEach(t=>{t.showPoints(e)})};onAddSpline=e=>{const t=JSON.parse(e.value),s=`Spline ${Ea+1}`,i=[];t.points.forEach(r=>{i.push(new y.Vector3(r[0],r[1],r[2]))});const n=new Ga(s,this.camera);n.addPoints(i),this.addSpline(n),Ea++};isMouseDown=!1;enableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.addEventListener("mousedown",this.onClickCanvas),e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("mouseup",this.onMouseUp)})}disableClickToDraw(){document.querySelectorAll(".clickable").forEach(e=>{e.removeEventListener("mousedown",this.onClickCanvas),e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("mouseup",this.onMouseUp)})}onClickCanvas=e=>{if(e.button!==0)return;if(this._camera.type!=="OrthographicCamera"){console.warn("Spline Editor - 3D Camera not supported in Draw Mode");return}const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1;if(tt.instance){const a=new y.Raycaster;a.setFromCamera(new y.Vector2(i,n),this._camera);const l=a.intersectObjects(tt.instance.helpersContainer.children,!0);for(let c=0;c<l.length;c++){const h=l[c];if(!(h.object.isLine||h.object.isTransformControlsPlane)&&h.object.isObject3D)return}}this.currentSpline===null&&(this.currentSpline=this.createSpline());const r=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.addPoint(r),this.isMouseDown=!0};onMouseMove=e=>{if(!this.isMouseDown)return;const s=e.target.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*2-1,n=-((e.clientY-s.top)/s.height)*2+1,r=this.mouseToSplinePos(i,n,s.width,s.height);this.currentSpline?.updateLastPoint(r)};onMouseUp=()=>{this.isMouseDown=!1};mouseToSplinePos(e,t,s,i){const n=new y.Vector3,r=Math.PI/2,a=this._camera,l=a.zoom,c=a.rotation.x===-6123233995736766e-32&&a.rotation.y===0&&a.rotation.z===0,h=a.rotation.x===-Math.PI&&a.rotation.y===12246467991473532e-32&&a.rotation.z===Math.PI,u=a.rotation.x===-6162975822039155e-48&&a.rotation.y===-r&&a.rotation.z===0,d=a.rotation.x===-6162975822039155e-48&&a.rotation.y===r&&a.rotation.z===0,p=a.rotation.x===-1.5707953264174506&&a.rotation.y===0&&a.rotation.z===0,f=a.rotation.x===1.5707953264174506&&a.rotation.y===0&&a.rotation.z===0;let m=e,x=t;h||d?m*=-1:p&&(x*=-1);const g=s/2/l,_=i/2/l;if(this.currentSpline===null&&(this.currentSpline=this.createSpline()),c||h){const b=m*g+a.position.x,T=x*_+a.position.y;n.set(b,T,0)}else if(u||d){const b=m*g+a.position.z,T=x*_+a.position.y;n.set(0,T,b)}else if(p||f){const b=m*g+a.position.x,T=x*_+a.position.z;n.set(b,0,T)}return n}get camera(){return this._camera}set camera(e){this._camera=e,this.children.forEach(t=>{const s=t;s.camera=e})}}const em=["Single","Side by Side","Stacked","Quad"],jN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAC60lEQVRYhe2YT4hNcRTHP48xpmYaNAvRyEQxEhnKQljYsRm9/EmSyJiMFAsMZWNhJYoNIUVJ2VGiyb9ZzIpMpkQSahbGv9GMYWrM+1rc2zjvzvvdd+99rzdvMd+6de75nd+5387vnN/v/G5KEuWMKRNNIB8mCRaKiiL5qQb2ApuBuUAV0Ad0AJeB3sSeJRX6LJbULTf6JTUn9Z+KWMUpPyp/Avoa4CNQZ3Sj/lNpdL/xottR7AjOkHRUUpekN5I6JbVLavDH75lIfZN0UFKTpCWS0pJem/HeJBEMG6yV1ONYtgFJbZJ+GF1jDh+zJb03NuliEuwMkMo4yErS2RA/LcbuYVyCrm1mA7Dal/8Cu4FG4JD/HsTTkCy6a+SVMTPQuc1sBKb78nHghi+/A+YBxwL2lbhRY+ThuARdEVxu5JdGFvACr0otdoZ8Y4+Rn0Sn5sFFsMvI6YB9MzA1YJ8mN8k1wAHzfj4uQVdyrpI0aJL7oqTtkq4FiqPLyCOSbktqlbRL0jlJQ2b8QdwCUZ4qvhRStZL0XFK1pMd57CRvq5mfhKBriRfiFUMY6oD7eOdwPlQAN4G10dfWg+uouwXsiOssAj4AC+JMcEWwvnAuOTEr7gTXPmg34zagOwkbIIOXAo9CbDYBrcBXYN+4UUdy2sRflyS5zVNlfPX7ugpJW5V9nI7mmh+lYU0lCZ2B3TOnAVuAk0BTwC5nuhWro46KauBOQJch5OpRaoIW34GreGf+YZdRqS9NAj4Bp4ClQDvwOWxCqSM4ADQEdKE5XvbXzlITrAVe4TW+M6NMKDXBFLAMuAD0ACfIc7pMZBXXA2cY3/xmodQRHAL2A2+NLtj8ZiEKwUL/z2WMPAJcAVYALWSf8dZuDFGWeBHwKxm3sWYhiGG8Tfo6sA2vSfiSy4GrH3wGrDcfKSSKKf6v1E9yF0XK9Q1XBPuMXMw8HXTonQFwETwNzMFr64v1jzgFHIk9ybHEZYPJo65QlD3Bf2/Q/eaHPiSWAAAAAElFTkSuQmCC",qN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAETklEQVRYhe2YXYhVVRTHf3d0/JhyUrMpFbImM+whSa3Mynww+4AeIgiKoozooQ+KyMyXIAujF6OXqHyI6iEKKYgIP/owsjSFqCkprdDUTEcjbWZ0HHV+Pex1ucfb9Z57Z9REXHA4Z++99l7/s/ZZ/7X2KaiczNLwfwPIk9MA+yunNMAG4DHgV+BvoB3YFff2TPstYEyfrajVroI6Sr1GvahsbJC63HzZq04pmztSvU5tVRuqYRiYg78JeBR4HPg5ntdmxovz9wJfA3uAxuibDLQCA+IqynnAQuBuYCnwMLC1rx48U12U8cZqdWqMDcx4cI16qTpYbVKHqa+ovWUeHKsujn7VL9ULq2HI+wY7gVeBJdGeFu3J4ZUiy/cAXeHRRuAQsC/GC0B3eG4BcH/0tUV7czUAeVsMsBF4Kha9HZgCvAncAuwPnXHA0wFuGLANuDrGuoGDwFxgTqzzQ7RX5FrP2eLsdb76vnogtme6+nE8H1YPlQXHwbi3q9eqn0e7Tb25VrsF68vFY0lb1AGcDTwItGQ8tQM4AIwGmqP/EPAu8A0wElgJfFGzxTo8mKWXu9Rd4ZF96jvqjSbauEC9Sn1O3R463epLaku99voCsFXdkAH3kNpcQW+IiT/bQne3eufxBtioPqP2mKhioXpWzpxb1T8C5Ifh4ZptVoriRmAIKdrI3Lujf3bobAPeJpF0NVkKrAFuI9HTOBIxnxFrF4OgQKKr/dnJlQA+AcwABgOHA4zAamA5cE7orQL+zAEHiWI+A2bFC7aSguheYCgpqAphZz3wSB7AecCICv2TgH8oFRib4gVqka0k0h8CXAxMBW6ooDejFoCvA9OBQUAvKWM0kDz4XUZvNKXtyZMWUl7vBbaQXq457PeEziDgx/KJlQAuIPFdMcEXv5OdYWBP9M8k8VpnDQCvB4aTSrCNJB5cSdrW3tBpIJVnR0qdUTxAfdGUOVTnmwqEanNmqltC/9OgqePKg5eom8PgdvW+oJ9Kupera0O3U50TL3lcAaI+oHaF4R3qa6Z822wq0Saq89T1lmSxOrxeW/Xm4uGkiqQDmECKuKHxHW0HdpMiewSpvGqKeR8Ay0iBsYIjg6261PE2o9Q3Yqv+MqWxO9R1Hl12qs+q49Vlppy82pSr+5xJKsko4AXgHlJ0t5NIeg3wLXAlqZhtIUV8J6nmWwX8QiLjdhL5TwMWkY4R6/rrwYKlMr1Y321QZ/vfwBijPqm+rF4Wc7PjE9QllurGVeoV5gRNHsAm9fnMom3qrKPoTjKdMXaYyrFygEWQ72XWW24qhPu8xcUc2UU6O8wFPjmK7jhgPHAuMJGUGQ6U6WwE5sfzTXGvei7KA9hFOiR9D/wOfFVFt4dS2tpfRe83Ur7/CPiJakfOGgBCypubatArl2r8VfOax/LfzABKtePAzHO/5FgC7KBEzB2kOrDfUm8mOeFySv9+OyFyGmB/5aQH+C9BVKmVCNuMZgAAAABJRU5ErkJggg==",YN="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAQ0lEQVQ4jWP8////fwYqAxYozUhFM/8zkaKYWIWkGEq0b0ZdSjQY5i79TyWagRGaTUdzFEEw6lLqGzqwLoVVJ1StpwA9sBwbUqAh5gAAAABJRU5ErkJggg==";class tt extends W.Component{static instance=null;scene;renderer;currentScene;scenes=new Map;cameras=new Map;controls=new Map;currentCamera;currentWindow;helpersContainer=new y.Group;cameraHelpers=new Map;lightHelpers=new Map;grid=new Xy;interactionHelper=new y.AxesHelper(25);currentTransform;splineEditor;depthMaterial=new y.MeshDepthMaterial;normalsMaterial=new y.MeshNormalMaterial;uvMaterial=new Zy;wireframeMaterial=new y.MeshBasicMaterial({opacity:.33,transparent:!0,wireframe:!0});playing=!1;rafID=-1;cameraControlsRafID=-1;width=0;height=0;tlCam=null;trCam=null;blCam=null;brCam=null;tlRender="Renderer";trRender="Renderer";blRender="Renderer";brRender="Renderer";cameraVisibility=!0;lightVisibility=!0;gridVisibility=!0;selectedItem=void 0;debugCamera;raycaster=new y.Raycaster;pointer=new y.Vector2;cameraControls=void 0;canvasRef;containerRef;tlWindow;trWindow;blWindow;brWindow;editorCameras=["Top","Bottom","Left","Right","Front","Back","Orthographic","UI","Debug"];constructor(e){super(e),this.props.three.addEventListener(ce.ADD_RENDERER,this.setupRenderer),this.scene=new y.Scene,this.scene.name=this.scene.uuid="",this.canvasRef=W.createRef(),this.containerRef=W.createRef(),this.tlWindow=W.createRef(),this.trWindow=W.createRef(),this.blWindow=W.createRef(),this.brWindow=W.createRef();const t=e.three.name,s=localStorage,i=s.getItem(`${t}_mode`);this.state={mode:i!==null?i:"Single",modeOpen:!1,renderModeOpen:!1,interactionMode:"Orbit",interactionModeOpen:!1,lastUpdate:Date.now()},s.setItem(`${t}_mode`,this.state.mode),s.setItem(`${t}_tlCam`,s.getItem(`${t}_tlCam`)!==null?s.getItem(`${t}_tlCam`):"Debug"),s.setItem(`${t}_trCam`,s.getItem(`${t}_trCam`)!==null?s.getItem(`${t}_trCam`):"Orthographic"),s.setItem(`${t}_blCam`,s.getItem(`${t}_blCam`)!==null?s.getItem(`${t}_blCam`):"Front"),s.setItem(`${t}_brCam`,s.getItem(`${t}_brCam`)!==null?s.getItem(`${t}_brCam`):"Top"),s.setItem(`${t}_tlRender`,s.getItem(`${t}_tlRender`)!==null?s.getItem(`${t}_tlRender`):"Renderer"),s.setItem(`${t}_trRender`,s.getItem(`${t}_trRender`)!==null?s.getItem(`${t}_trRender`):"Renderer"),s.setItem(`${t}_blRender`,s.getItem(`${t}_blRender`)!==null?s.getItem(`${t}_blRender`):"Renderer"),s.setItem(`${t}_brRender`,s.getItem(`${t}_brRender`)!==null?s.getItem(`${t}_brRender`):"Renderer");const n={Vector2:y.Vector2,Vector3:y.Vector3,Vector4:y.Vector4,Quaternion:y.Quaternion,Matrix4:y.Matrix4,Spherical:y.Spherical,Box3:y.Box3,Sphere:y.Sphere,Raycaster:y.Raycaster};Ds.install({THREE:n}),this.setupScene(),this.setupTools();const r=localStorage.getItem(this.expandedCameraVisibility);r!==null&&(this.cameraVisibility=r==="open"),this.saveExpandedCameraVisibility();const a=localStorage.getItem(this.expandedLightVisibility);a!==null&&(this.lightVisibility=a==="open"),this.saveExpandedLightVisibility();const l=localStorage.getItem(this.expandedGridVisibility);l!==null&&(this.gridVisibility=l==="open"),this.grid.visible=this.gridVisibility,this.saveExpandedGridVisibility(),tt.instance=this}componentDidMount(){this.enable(),this.assignControls(),this.resize(),this.play(),mt.instance.setApp(this.props.three),mt.instance.activeCamera=this.debugCamera}componentDidUpdate(e,t,s){t.mode!==this.state.mode&&(this.assignControls(),this.resize())}componentWillUnmount(){this.disable(),this.clear(),Ne.removeEditorGroup("View Settings")}render(){const e=[];return this.cameras.forEach((t,s)=>{e.push(s)}),E.jsxs("div",{className:"multiview",children:[E.jsx("canvas",{ref:this.canvasRef}),E.jsxs("div",{className:`cameras ${this.state.mode==="Single"||this.state.mode==="Stacked"?"single":""}`,ref:this.containerRef,children:[this.state.mode==="Single"&&E.jsx(E.Fragment,{children:E.jsx(Ki,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}})}),(this.state.mode==="Side by Side"||this.state.mode==="Stacked")&&E.jsxs(E.Fragment,{children:[E.jsx(Ki,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),E.jsx(Ki,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}})]}),this.state.mode==="Quad"&&E.jsxs(E.Fragment,{children:[E.jsx(Ki,{name:"tl",camera:this.tlCam,options:e,ref:this.tlWindow,onSelectCamera:t=>{this.controls.get(this.tlCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.tlCam),this.tlCam=s,localStorage.setItem(`${this.appID}_tlCam`,s.name),this.createControls(s,this.tlWindow.current))},onSelectRenderMode:t=>{this.tlRender=t,localStorage.setItem(`${this.appID}_tlRender`,t)}}),E.jsx(Ki,{name:"tr",camera:this.trCam,options:e,ref:this.trWindow,onSelectCamera:t=>{this.controls.get(this.trCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.trCam),this.trCam=s,localStorage.setItem(`${this.appID}_trCam`,s.name),this.createControls(s,this.trWindow.current))},onSelectRenderMode:t=>{this.trRender=t,localStorage.setItem(`${this.appID}_trRender`,t)}}),E.jsx(Ki,{name:"bl",camera:this.blCam,options:e,ref:this.blWindow,onSelectCamera:t=>{this.controls.get(this.blCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.blCam),this.blCam=s,localStorage.setItem(`${this.appID}_blCam`,s.name),this.createControls(s,this.blWindow.current))},onSelectRenderMode:t=>{this.blRender=t,localStorage.setItem(`${this.appID}_blRender`,t)}}),E.jsx(Ki,{name:"br",camera:this.brCam,options:e,ref:this.brWindow,onSelectCamera:t=>{this.controls.get(this.brCam.name)?.dispose();const s=this.cameras.get(t);s!==void 0&&(this.clearCamera(this.brCam),this.brCam=s,localStorage.setItem(`${this.appID}_brCam`,s.name),this.createControls(s,this.brWindow.current))},onSelectRenderMode:t=>{this.brRender=t,localStorage.setItem(`${this.appID}_brRender`,t)}})]})]}),E.jsxs("div",{className:"settings",children:[E.jsx(hl,{title:"View",index:em.indexOf(this.state.mode),options:em,onSelect:t=>{t!==this.state.mode&&(this.killControls(),this.setState({mode:t}),localStorage.setItem(`${this.appID}_mode`,t))},open:this.state.modeOpen,onToggle:t=>{this.setState({modeOpen:t,renderModeOpen:!1,interactionModeOpen:!1})}}),E.jsx(hl,{title:"Interact",index:this.state.interactionMode==="Orbit"?0:1,options:["Orbit Mode","Selection Mode"],onSelect:t=>{this.interactionHelper.visible=t==="Selection Mode",this.setState({interactionMode:this.interactionHelper.visible?"Selection":"Orbit"})},open:this.state.interactionModeOpen,onToggle:t=>{this.setState({modeOpen:!1,renderModeOpen:!1,interactionModeOpen:t})}}),E.jsx(oh,{name:"cameraHelper",icon:jN,selected:this.cameraVisibility,height:24,top:2,onClick:t=>{if(this.cameraVisibility=t,this.saveExpandedCameraVisibility(),this.cameraHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t){const s=this.cameraHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),E.jsx(oh,{name:"lightHelper",icon:qN,selected:this.lightVisibility,height:24,top:4,onClick:t=>{if(this.lightVisibility=t,this.saveExpandedLightVisibility(),this.lightHelpers.forEach(s=>{s.visible=t}),this.selectedItem!==void 0&&!t&&this.selectedItem.isLight===!0){const s=this.lightHelpers.get(this.selectedItem.name);s!==void 0&&(s.visible=!0)}}}),E.jsx(oh,{name:"gridHelper",icon:YN,selected:this.gridVisibility,height:21,width:21,onClick:t=>{this.gridVisibility=t,this.saveExpandedGridVisibility(),this.grid.visible=t}})]},this.state.lastUpdate)]})}setupRenderer=e=>{this.renderer&&this.renderer.dispose();const t=this.canvasRef.current;this.props.three.canvas=t;const s=e.value;s.type==="WebGLRenderer"?(this.renderer=new y.WebGLRenderer({canvas:t,stencil:!1}),this.grid.visible=!0):s.type==="WebGPURenderer"&&(this.renderer=new xa({canvas:t,stencil:!1}),this.grid.visible=!1),this.renderer&&(this.renderer.autoClear=!1,this.renderer.shadowMap.enabled=!0,this.renderer.setPixelRatio(devicePixelRatio),this.renderer.setClearColor(0),this.resize(),this.props.three.renderer=this.renderer)};setupScene(){this.helpersContainer.name="helpers",this.scene.add(this.helpersContainer),this.grid.position.y=-1,this.scene.add(this.grid),this.interactionHelper.name="interactionHelper",this.interactionHelper.visible=!1,this.helpersContainer.add(this.interactionHelper);const e=(n,r)=>{const a=new y.OrthographicCamera(-100,100,100,-100,0,3e3);return a.name=n,a.position.copy(r),a.lookAt(0,0,0),this.cameras.set(n,a),a},t=1e3;e("Top",new y.Vector3(0,t,0)),e("Bottom",new y.Vector3(0,-t,0)),e("Left",new y.Vector3(-t,0,0)),e("Right",new y.Vector3(t,0,0)),e("Front",new y.Vector3(0,0,t)),e("Back",new y.Vector3(0,0,-t)),e("Orthographic",new y.Vector3(t,t,t)),e("UI",new y.Vector3),this.debugCamera=new y.PerspectiveCamera(60,1,.01,3e3),this.debugCamera.name="Debug",this.debugCamera.position.set(300,300,300),this.debugCamera.lookAt(0,0,0),this.cameras.set("Debug",this.debugCamera),this.currentCamera=this.debugCamera;const s=localStorage,i=this.props.three.name;this.tlCam=this.cameras.get(s.getItem(`${i}_tlCam`)),this.trCam=this.cameras.get(s.getItem(`${i}_trCam`)),this.blCam=this.cameras.get(s.getItem(`${i}_blCam`)),this.brCam=this.cameras.get(s.getItem(`${i}_brCam`)),this.tlCam===void 0&&(this.tlCam=this.cameras.get("Debug")),this.trCam===void 0&&(this.trCam=this.cameras.get("Orthographic")),this.blCam===void 0&&(this.blCam=this.cameras.get("Front")),this.brCam===void 0&&(this.brCam=this.cameras.get("Top"))}setupTools(){this.splineEditor=new Ky(this.currentCamera,this.three),this.splineEditor.initDebug(),this.helpersContainer.add(this.splineEditor)}play(){this.playing=!0,this.onUpdate()}pause(){this.playing=!1,cancelAnimationFrame(this.rafID),this.rafID=-1}toggleOrbitControls(e){this.controls.forEach(t=>{t.enabled=!e})}clear(){this.three.dispatchEvent({type:ce.CLEAR_OBJECT}),Ne.removeAllGroups(),this.clearLightHelpers(),this.clearControls(),this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),mt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=void 0,mt.instance.clear(),this.cameras.forEach(e=>{this.editorCameras.indexOf(e.name)<0&&this.three.dispatchEvent({type:ce.REMOVE_CAMERA,value:e})}),this.currentCamera=this.debugCamera,this.currentScene=void 0,this.scenes.forEach(e=>{this.three.dispatchEvent({type:ce.REMOVE_SCENE,value:e})}),this.scenes.clear()}update(){this.renderer&&(this.renderer instanceof y.WebGLRenderer?this.renderer?.clear():this.renderer instanceof xa&&this.renderer?.clearAsync()),this.controls.forEach(e=>e.update()),this.cameraHelpers.forEach(e=>e.update()),this.lightHelpers.forEach(e=>{e.update!==void 0&&e.update()}),this.props.onSceneUpdate!==void 0&&this.currentScene!==void 0&&this.props.onSceneUpdate(this.currentScene)}draw(){switch(this.renderer&&(this.renderer instanceof y.WebGLRenderer?this.renderer?.clear():this.renderer instanceof xa&&this.renderer?.clearAsync()),this.state.mode){case"Single":this.drawSingle();break;case"Side by Side":case"Stacked":this.drawDouble();break;case"Quad":this.drawQuad();break}}onUpdate=()=>{this.playing&&(this.update(),this.draw(),this.rafID=requestAnimationFrame(this.onUpdate))};enable(){const e=this.containerRef.current;e.addEventListener("mousemove",this.onMouseMove),e.addEventListener("click",this.onClick),window.addEventListener("keydown",this.onKey),window.addEventListener("resize",this.resize),this.three.addEventListener(ce.ADD_SCENE,this.addScene),this.three.addEventListener(ce.SET_SCENE,this.sceneUpdate),this.three.addEventListener(ce.REMOVE_SCENE,this.removeScene),this.three.addEventListener(ce.ADD_CAMERA,this.addCamera),this.three.addEventListener(ce.REMOVE_CAMERA,this.removeCamera),this.three.addEventListener(ce.SET_OBJECT,this.onSetSelectedItem)}disable(){const e=this.containerRef.current;e.removeEventListener("mousemove",this.onMouseMove),e.removeEventListener("click",this.onClick),window.removeEventListener("keydown",this.onKey),window.removeEventListener("resize",this.resize),this.three.removeEventListener(ce.ADD_SCENE,this.addScene),this.three.removeEventListener(ce.SET_SCENE,this.sceneUpdate),this.three.removeEventListener(ce.ADD_CAMERA,this.addCamera),this.three.removeEventListener(ce.REMOVE_CAMERA,this.removeCamera),this.three.removeEventListener(ce.SET_OBJECT,this.onSetSelectedItem)}resize=()=>{this.width=window.innerWidth-300,this.height=window.innerHeight,this.renderer?.setSize(this.width,this.height);const e=Math.floor(this.width/2),t=Math.floor(this.height/2);this.props.three.resize(this.width,this.height),this.props.onSceneResize!==void 0&&this.currentScene!==void 0&&this.props.onSceneResize(this.currentScene,this.width,this.height);let s=this.width,i=this.height;switch(this.state.mode){case"Side by Side":s=e,i=this.height;break;case"Stacked":s=this.width,i=t;break;case"Quad":s=e,i=t;break}const n=s/i;this.cameras.forEach(r=>{r instanceof y.OrthographicCamera?(r.left=s/-2,r.right=s/2,r.top=i/2,r.bottom=i/-2,r.name==="UI"&&(r.position.x=this.width/2,r.position.y=this.height/-2,r.position.z=100),r.updateProjectionMatrix()):r instanceof y.PerspectiveCamera&&(r.aspect=n,r.updateProjectionMatrix()),this.cameraHelpers.get(r.name)?.update()})};addScene=e=>{const t=this.props.scenes.get(e.value.name);if(t!==void 0){const s=new t;s.visible=!1,this.props.onSceneAdd!==void 0&&this.props.onSceneAdd(s),this.props.three.scene=s,this.scenes.set(e.value.name,s),this.scene.add(s)}else console.log("Hermes - Scene not found:",e.value.name,this.props.scenes)};sceneUpdate=e=>{this.currentScene!==void 0&&(this.currentScene.visible=!1,this.clearLightHelpers());const t=this.scene.getObjectByName(e.value.name);t!==void 0&&(this.currentScene=t,this.currentScene.visible=!0,this.addLightHelpers(this.currentScene))};removeScene=e=>{const t=e.value.name;this.scenes.delete(t);const s=this.scene.getObjectByName(t);s&&setTimeout(()=>{Ls(s)},100),this.clearLightHelpers()};addCamera=e=>{const t=e.value,s=t.uuid,i=this.props.three.scene?.getObjectByProperty("uuid",t.uuid);if(i!==void 0){const n=i;this.cameras.set(s,n);const r=new y.CameraHelper(n);r.visible=this.cameraVisibility,this.cameraHelpers.set(s,r),this.helpersContainer.add(r),this.setState({lastUpdate:Date.now()})}};removeCamera=e=>{const s=e.value.uuid,i=this.cameraHelpers.get(s);i!==void 0&&(this.helpersContainer.remove(i),i.dispose()),this.cameras.delete(s),this.setState({lastUpdate:Date.now()})};onMouseMove=e=>{const t=new y.Vector2;this.renderer?.getSize(t);const s=Math.min(e.clientX,t.x),i=Math.min(e.clientY,t.y);this.pointer.x=Ji(s,0,t.x,-1,1),this.pointer.y=Ji(i,0,t.y,1,-1);const n=t.x/2,r=t.y/2,a=()=>{s<n?this.pointer.x=Ji(s,0,n,-1,1):this.pointer.x=Ji(s,n,t.x,-1,1)},l=()=>{i<r?this.pointer.y=Ji(i,0,r,1,-1):this.pointer.y=Ji(i,r,t.y,1,-1)};switch(this.state.mode){case"Quad":a(),l();break;case"Side by Side":a();break;case"Stacked":l(),l();break}if(this.updateCamera(s,i,n,r),this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const c=this.raycaster.intersectObjects(this.currentScene.children);c.length>0&&this.interactionHelper.position.copy(c[0].point)};onClick=e=>{if(this.state.interactionMode==="Orbit"||this.currentScene===void 0)return;const t=new y.Vector2;if(this.renderer.getSize(t),e.clientX>=t.x)return;this.onMouseMove(e);const s=this.raycaster.intersectObjects(this.currentScene.children);s.length>0&&(this.props.three.getObject(s[0].object.uuid),this.interactionHelper.visible=!1,this.setState({interactionMode:"Orbit",lastUpdate:Date.now()}))};onKey=e=>{if(this.selectedItem!==void 0){if(e.ctrlKey){if(this.currentCamera.name==="UI")return;const t=this.controls.get(this.currentCamera.name);e.key==="0"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.selectedItem instanceof y.Mesh||this.selectedItem instanceof y.SkinnedMesh?(this.selectedItem.geometry.computeBoundingBox(),this.cameraControls.fitToBox(this.selectedItem.geometry.boundingBox,!0)):this.cameraControls.fitToSphere(this.selectedItem,!0),this.updateCameraControls(t,!0)):e.key==="1"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,Math.PI*.5,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="2"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(0,0,!0),this.cameraControls.moveTo(this.selectedItem.position.x,0,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="3"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI/2,Math.PI/2,!0),this.cameraControls.moveTo(0,this.selectedItem.position.y,this.selectedItem.position.z,!0),this.updateCameraControls(t)):e.key==="4"?(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Math.PI,Math.PI/2,!0),this.cameraControls.moveTo(this.selectedItem.position.x,this.selectedItem.position.y,0,!0),this.updateCameraControls(t)):e.key==="5"&&(e.preventDefault(),this.clearControls(),this.cameraControls=new Ds(this.currentCamera,this.currentWindow.current),this.cameraControls.rotateTo(Wa(45),Wa(45),!0),this.updateCameraControls(t))}else if(this.currentTransform!==void 0)switch(e.key){case"r":this.currentTransform.setMode("rotate");break;case"s":this.currentTransform.setMode("scale");break;case"t":this.currentTransform.setMode("translate");break;case"q":this.currentTransform.setSpace(this.currentTransform.space==="local"?"world":"local");break}}};onSetSelectedItem=e=>{this.selectedItem!==void 0&&this.updateSelectedItemHelper(!1),this.selectedItem=void 0;const t=e.value.uuid;if(this.scenes.forEach(s=>{t.search(s.uuid)>-1&&(this.selectedItem=s.getObjectByProperty("uuid",t))}),this.selectedItem===void 0){console.log(`Hermes - Can't find selected item: ${e.value.uuid}, ${e.value.name}`);return}this.currentTransform!==void 0&&(this.currentTransform.removeEventListener("objectChange",this.onUpdateTransform),mt.instance.remove(this.currentTransform.getHelper().name)),this.currentTransform=mt.instance.add(e.value.name),this.currentTransform.attach(this.selectedItem),this.helpersContainer.add(this.currentTransform.getHelper()),this.currentTransform.addEventListener("objectChange",this.onUpdateTransform),this.updateSelectedItemHelper(!0)};updateSelectedItemHelper(e){if(this.selectedItem!==void 0)if(this.cameraVisibility){if(this.selectedItem.isLight===!0&&!this.lightVisibility){const t=this.lightHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}else{const t=this.cameraHelpers.get(this.selectedItem.name);t!==void 0&&(t.visible=e)}}onUpdateTransform=()=>{this.selectedItem!==void 0&&(this.props.three.updateObject(this.selectedItem.uuid,"position",this.selectedItem.position),this.props.three.updateObject(this.selectedItem.uuid,"rotation",{x:this.selectedItem.rotation.x,y:this.selectedItem.rotation.y,z:this.selectedItem.rotation.z}),this.props.three.updateObject(this.selectedItem.uuid,"scale",this.selectedItem.scale),Fl.instance.update())};clearLightHelpers=()=>{this.lightHelpers.forEach(e=>{this.helpersContainer.remove(e),e.dispose()}),this.lightHelpers.clear()};addLightHelpers=e=>{e.traverse(t=>{if(t.type.search("Light")>-1){let s;switch(t.type){case"DirectionalLight":s=new y.DirectionalLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"HemisphereLight":s=new y.HemisphereLightHelper(t,250),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"RectAreaLight":s=new fN(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"PointLight":s=new y.PointLightHelper(t,100),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break;case"SpotLight":s=new y.SpotLightHelper(t),s.name=`${t.name}Helper`,s.visible=this.lightVisibility,this.lightHelpers.set(t.name,s),this.helpersContainer.add(s);break}}})};createControls(e,t){const s=this.controls.get(e.name);if(s!==void 0&&s.dispose(),this.controls.delete(e.name),e.name==="UI")return;const i=new gN(e,t);switch(i.enableDamping=!0,i.dampingFactor=.1,e.name){case"Top":case"Bottom":case"Left":case"Right":case"Front":case"Back":i.enableRotate=!1;break}this.controls.set(e.name,i)}clearCamera(e){const t=this.cameraHelpers.get(e.name);t!==void 0&&(this.helpersContainer.remove(t),t.dispose(),this.cameraHelpers.delete(e.name));const s=this.controls.get(e.name);s!==void 0&&(s.dispose(),this.controls.delete(e.name))}killControls(){this.controls.forEach((e,t)=>{e.dispose();const s=this.cameraHelpers.get(t);s!==void 0&&(this.helpersContainer.remove(s),s.dispose()),this.cameraHelpers.delete(t),this.controls.delete(t)}),this.controls.clear(),this.cameraHelpers.clear()}assignControls(){switch(this.state.mode){case"Single":this.createControls(this.tlCam,this.tlWindow.current);break;case"Side by Side":case"Stacked":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current);break;case"Quad":this.createControls(this.tlCam,this.tlWindow.current),this.createControls(this.trCam,this.trWindow.current),this.createControls(this.blCam,this.blWindow.current),this.createControls(this.brCam,this.brWindow.current);break}}updateCamera=(e,t,s,i)=>{switch(this.state.mode){case"Quad":t<i?e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam:e<s?this.currentCamera=this.blCam:this.currentCamera=this.brCam;break;case"Side by Side":e<s?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break;case"Single":this.currentCamera=this.tlCam;break;case"Stacked":t<i?this.currentCamera=this.tlCam:this.currentCamera=this.trCam;break}this.splineEditor.camera=this.currentCamera,this.raycaster.setFromCamera(this.pointer,this.currentCamera),this.currentCamera===this.tlCam?this.currentWindow=this.tlWindow:this.currentCamera===this.trCam?this.currentWindow=this.trWindow:this.currentCamera===this.blCam?this.currentWindow=this.blWindow:this.currentCamera===this.brCam&&(this.currentWindow=this.brWindow),mt.instance.updateCamera(this.currentCamera,this.currentWindow.current)};updateCameraControls=(e,t=!1)=>{if(this.selectedItem===void 0)return;cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.cameraControls&&(this.cameraControls.smoothTime=.1);const s=.15,i=new y.Clock;i.start(),this.selectedItem.getWorldPosition(e.target0);const n=()=>{const r=i.getDelta();this.cameraControls&&this.cameraControls.update(r),t&&(e.target.lerp(e.target0,s),e.object.position.lerp(e.position0,s),e.object.zoom=lr(e.object.zoom,e.zoom0,s),e.object.updateProjectionMatrix(),e.dispatchEvent({type:"change"})),i.getElapsedTime()>=.5?(cancelAnimationFrame(this.cameraControlsRafID),this.cameraControlsRafID=-1,this.clearControls()):this.cameraControlsRafID=requestAnimationFrame(n)};n()};clearControls=()=>{this.cameraControls!==void 0&&(this.cameraControls.disconnect(),this.cameraControls.dispose(),this.cameraControls=void 0)};saveExpandedCameraVisibility(){localStorage.setItem(this.expandedCameraVisibility,this.cameraVisibility?"open":"closed")}saveExpandedLightVisibility(){localStorage.setItem(this.expandedLightVisibility,this.lightVisibility?"open":"closed")}saveExpandedGridVisibility(){localStorage.setItem(this.expandedGridVisibility,this.gridVisibility?"open":"closed")}getSceneOverride(e){switch(e){case"Depth":return this.depthMaterial;case"Normals":return this.normalsMaterial;case"Renderer":return null;case"UVs":return this.uvMaterial;case"Wireframe":return this.wireframeMaterial}return null}drawTo(e,t,s,i,n,r){switch(n.name){case"Left":case"Right":this.grid.rotation.z=Math.PI/2;break;case"Front":case"Back":this.grid.rotation.x=Math.PI/2;break}this.scene.overrideMaterial=r,this.renderer&&(this.renderer?.setViewport(e,t,s,i),this.renderer?.setScissor(e,t,s,i),this.renderer instanceof y.WebGLRenderer?this.renderer?.render(this.scene,n):this.renderer instanceof xa&&this.renderer?.renderAsync(this.scene,n)),this.grid.rotation.set(0,0,0)}drawSingle(){const e=this.getSceneOverride(this.tlRender);this.drawTo(0,0,this.width,this.height,this.tlCam,e)}drawDouble=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=Math.floor(this.width/2),i=Math.floor(this.height/2);if(this.state.mode==="Side by Side")this.drawTo(0,0,s,this.height,this.tlCam,e),this.drawTo(s,0,s,this.height,this.trCam,t);else{const n=this.height-i;this.drawTo(0,n,this.width,i,this.tlCam,e),this.drawTo(0,0,this.width,i,this.trCam,t)}};drawQuad=()=>{const e=this.getSceneOverride(this.tlRender),t=this.getSceneOverride(this.trRender),s=this.getSceneOverride(this.blRender),i=this.getSceneOverride(this.brRender),n=Math.floor(this.width/2),r=Math.floor(this.height/2);let a=0,l=0;l=this.height-r,a=0,this.drawTo(a,l,n,r,this.tlCam,e),a=n,this.drawTo(a,l,n,r,this.trCam,t),l=0,a=0,this.scene.overrideMaterial=s,this.drawTo(a,l,n,r,this.blCam,s),a=n,this.drawTo(a,l,n,r,this.brCam,i)};get appID(){return this.props.three.name}get mode(){return this.state.mode}get three(){return this.props.three}get expandedCameraVisibility(){return`${this.appID}_multiviewCameraVisibility`}get expandedLightVisibility(){return`${this.appID}_multiviewLightVisibility`}get expandedGridVisibility(){return`${this.appID}_multiviewGridVisibility`}}class Fl extends W.Component{static instance;matrix=new y.Matrix4;position=new y.Vector3;rotation=new y.Euler;scale=new y.Vector3;open=!1;constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;this.open=s,this.saveExpanded(),this.state={lastUpdated:0,expanded:s},this.matrix.elements=e.object.matrix,e.object.uuid.length>0&&(this.position.setFromMatrixPosition(this.matrix),this.rotation.setFromRotationMatrix(this.matrix),this.scale.setFromMatrixScale(this.matrix)),Fl.instance=this}update(){if(tt.instance){const e=tt.instance.selectedItem;if(e===void 0)return;this.position.x=is(e.position.x,3),this.position.y=is(e.position.y,3),this.position.z=is(e.position.z,3),this.rotation.copy(e.rotation),this.scale.x=is(e.scale.x,3),this.scale.y=is(e.scale.y,3),this.scale.z=is(e.scale.z,3),this.setState({lastUpdated:Date.now()})}}render(){return E.jsx(hs,{three:this.props.three,title:"Transform",expanded:this.open,items:[{title:"Position",prop:"position",type:"grid3",step:.1,value:this.position,onChange:this.updateTransform},{title:"Rotation",prop:"rotation",type:"euler",value:this.rotation,onChange:this.updateTransform},{title:"Scale",prop:"scale",type:"grid3",value:this.scale,onChange:this.updateTransform},{title:"Visible",prop:"visible",type:"boolean",value:this.props.object.visible,onChange:this.updateTransform}],onToggle:e=>{this.open=e,this.saveExpanded()}},this.state.lastUpdated)}updateTransform=(e,t)=>{const s=e==="rotation"?{x:t._x,y:t._y,z:t._z}:t;this.props.three.updateObject(this.props.object.uuid,e,s);const i=this.props.three.getScene(this.props.object.uuid);if(i){const n=i.getObjectByProperty("uuid",this.props.object.uuid);Ye(n,e,s)}};saveExpanded(){localStorage.setItem(this.expandedName,this.open?"open":"closed")}get expandedName(){return`${this.props.three.name}_transform`}}function tm(o){switch(o){case"color":return"Color";case"intensity":return"Intensity";case"decay":return"Decay";case"distance":return"Distance";case"angle":return"Angle";case"penumbra":return"Penumbra";case"groundColor":return"Ground Color";case"width":return"Width";case"height":return"Height"}return o}function XN(o,e){function t(){return`${e.name}_light`}const s=localStorage.getItem(t()),i=s!==null?s==="open":!1;function n(a){localStorage.setItem(t(),a?"open":"closed")}const r=[];if(o.lightInfo!==void 0)for(const a in o.lightInfo){const l=o.lightInfo[a];l!==void 0&&(l.isColor!==void 0?r.push({title:tm(a),prop:a,type:"color",value:l,onChange:(c,h)=>{const u=new y.Color(h);e.updateObject(o.uuid,c,u);const d=e.getScene(o.uuid);if(d!==null){const p=d.getObjectByProperty("uuid",o.uuid);Ye(p,c,u)}}}):r.push({title:tm(a),prop:a,type:typeof l,value:l,step:typeof l=="number"?.01:void 0,onChange:(c,h)=>{e.updateObject(o.uuid,c,h);const u=e.getScene(o.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",o.uuid);Ye(d,c,h)}}}))}return E.jsx(hs,{three:e,title:"Light",items:r,expanded:i,onToggle:a=>{n(a)}})}function ZN(o){const e=o.object,t=o.three;function s(){return`${t.name}_animation`}const i=localStorage.getItem(s()),n=i!==null?i==="open":!1;function r(d){localStorage.setItem(s(),d?"open":"closed")}const a=[],l=[];let c=0;e.animations.forEach(d=>{c=Math.max(c,d.duration),d.duration>0&&l.push({title:d.name,items:[{title:"Duration",type:"number",value:d.duration,disabled:!0},{title:"Blend Mode",type:"option",disabled:!0,options:[{title:"Normal",value:2500},{title:"Additive",value:2501}]}]})}),a.push({title:"Animations",items:l});let h;const u=t.getScene(e.uuid);if(u!==null){const d=u.getObjectByProperty("uuid",e.uuid);if(d!==void 0){const p=d.mixer;if(p!==void 0){const m=[{title:"Time Scale",type:"range",value:p.timeScale,step:.01,min:-1,max:2,onChange:(x,g)=>{p.timeScale=g,t.updateObject(e.uuid,"mixer.timeScale",g)}}];m.push({title:"Stop All",type:"button",onChange:()=>{p.stopAllAction(),t.requestMethod(e.uuid,"stopAllAction",void 0,"mixer")}}),a.push({title:"Mixer",items:m}),h=new y.SkeletonHelper(d),tt.instance?.scene.add(h)}}}return W.useEffect(()=>()=>{h!==void 0&&Ls(h)},[]),E.jsx(hs,{three:o.three,title:"Animation",items:a,expanded:n,onToggle:d=>{r(d)}})}const hh={name:"",uuid:"",type:"",visible:!1,matrix:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],animations:[],material:void 0,perspectiveCameraInfo:void 0,orthographicCameraInfo:void 0,lightInfo:void 0,children:[]};function Qy(o){const[e,t]=W.useState(hh);W.useEffect(()=>{function r(l){t(l.value)}function a(){t(hh)}return o.three.addEventListener(ce.CLEAR_OBJECT,a),o.three.addEventListener(ce.SET_SCENE,a),o.three.addEventListener(ce.SET_OBJECT,r),()=>{o.three.removeEventListener(ce.CLEAR_OBJECT,a),o.three.removeEventListener(ce.SET_SCENE,a),o.three.removeEventListener(ce.SET_OBJECT,r)}},[]);const s=e.type.toLowerCase(),i=e.animations.length>0||e.mixer!==void 0,n=s.search("mesh")>-1||s.search("line")>-1||s.search("points")>-1;return E.jsx(Qn,{three:o.three,label:"Inspector",button:e.uuid.length>0?E.jsx("button",{className:"remove",onClick:()=>{mt.instance.remove(e.name),t(hh)}}):void 0,children:E.jsx("div",{id:"Inspector",className:o.class,children:e.uuid.length>0&&E.jsxs(E.Fragment,{children:[E.jsxs(E.Fragment,{children:[E.jsx(Ra,{type:"string",title:"Name",prop:"name",value:e.name,disabled:!0}),E.jsx(Ra,{type:"string",title:"Type",prop:"type",value:e.type,disabled:!0}),E.jsx(Ra,{type:"string",title:"UUID",prop:"uuid",value:e.uuid,disabled:!0})]}),E.jsxs(E.Fragment,{children:[E.jsx(Fl,{object:e,three:o.three}),i?E.jsx(ZN,{object:e,three:o.three}):null,s.search("camera")>-1?T_(e,o.three):null,s.search("light")>-1?XN(e,o.three):null,n?x_(e,o.three):null]})]})})},"Inspector")}class KN extends W.Component{autoClear=!0;autoClearColor=!0;autoClearDepth=!0;autoClearStencil=!0;outputColorSpace=y.SRGBColorSpace;localClippingEnabled=!1;clearColor=new y.Color(0);clearAlpha=1;toneMapping=y.NoToneMapping;toneMappingExposure=1;type="";constructor(e){super(e);const t=localStorage.getItem(this.expandedName),s=t!==null?t==="open":!1;if(this.state={expanded:s,lastUpdated:Date.now()},this.saveExpanded(s),tt.instance){const i=tt.instance.renderer;i&&(this.autoClear=i.autoClear,this.autoClearColor=i.autoClearColor,this.autoClearDepth=i.autoClearDepth,this.autoClearStencil=i.autoClearStencil,this.clearAlpha=i.getClearAlpha(),this.toneMapping=i.toneMapping,this.toneMappingExposure=i.toneMappingExposure,i instanceof y.WebGLRenderer&&(this.localClippingEnabled=i.localClippingEnabled,i.getClearColor(this.clearColor)))}this.props.three.addEventListener(ce.ADD_RENDERER,this.onAddRenderer)}componentwillunmount(){this.props.three.removeEventListener(ce.ADD_RENDERER,this.onAddRenderer)}onAddRenderer=e=>{const t=e.value;if(this.autoClear=t.autoClear,this.autoClearColor=t.autoClearColor,this.autoClearDepth=t.autoClearDepth,this.autoClearStencil=t.autoClearStencil,this.outputColorSpace=t.outputColorSpace,this.localClippingEnabled=t.localClippingEnabled,this.clearAlpha=t.clearAlpha,this.type=t.type,this.toneMapping=t.toneMapping,this.toneMappingExposure=t.toneMappingExposure,this.clearColor.setStyle(t.clearColor,y.LinearSRGBColorSpace),y.ColorManagement.enabled=t.colorManagement,tt.instance){const s=tt.instance.renderer;s&&(s.autoClearColor=this.autoClearColor,s.outputColorSpace=this.outputColorSpace,s.localClippingEnabled=this.localClippingEnabled,s.toneMapping=this.toneMapping,s.toneMappingExposure=this.toneMappingExposure,s.setClearColor(t.clearColor,this.clearAlpha))}this.setState({lastUpdated:Date.now()})};render(){const e=()=>{if(tt.instance){const t=tt.instance.renderer;t&&(t.autoClearColor=this.autoClearColor,t.outputColorSpace=this.outputColorSpace,t.localClippingEnabled=this.localClippingEnabled,t.toneMapping=this.toneMapping,t.toneMappingExposure=this.toneMappingExposure,t.setClearColor(this.clearColor.getStyle(),this.clearAlpha),this.props.three.updateRenderer({autoClear:this.autoClear,autoClearColor:this.autoClearColor,autoClearDepth:this.autoClearDepth,autoClearStencil:this.autoClearStencil,outputColorSpace:this.outputColorSpace,localClippingEnabled:this.localClippingEnabled,clearAlpha:this.clearAlpha,clearColor:this.clearColor.getStyle(),colorManagement:y.ColorManagement.enabled,toneMapping:this.toneMapping,toneMappingExposure:this.toneMappingExposure}))}};return E.jsx(hs,{three:this.props.three,title:"Renderer",expanded:this.state.expanded,items:[{type:"boolean",title:"Auto Clear",value:this.autoClear,onChange:(t,s)=>{this.autoClear=s}},{type:"boolean",title:"Auto Clear Color",value:this.autoClearColor,onChange:(t,s)=>{this.autoClearColor=s,e()}},{type:"boolean",title:"Auto Clear Depth",value:this.autoClearDepth,onChange:(t,s)=>{this.autoClearDepth=s,e()}},{type:"boolean",title:"Auto Clear Stencil",value:this.autoClearStencil,onChange:(t,s)=>{this.autoClearStencil=s,e()}},{type:"boolean",title:"Local Clipping",value:this.localClippingEnabled,onChange:(t,s)=>{this.localClippingEnabled=s,e()}},{type:"color",title:"Clear Color",value:`#${this.clearColor.getHexString()}`,onChange:(t,s)=>{this.clearColor.setStyle(s),e()}},{type:"range",title:"Clear Alpha",min:0,max:1,step:.01,value:this.clearAlpha,onChange:(t,s)=>{this.clearAlpha=s,e()}},{type:"boolean",title:"Clear Management",value:y.ColorManagement.enabled,onChange:(t,s)=>{y.ColorManagement.enabled=s,e()}},{type:"option",title:"Color Space",value:this.outputColorSpace,options:[{title:"No Color Space",value:y.NoColorSpace},{title:"SRB Color Space",value:y.SRGBColorSpace},{title:"Linear SRB Color Space",value:y.LinearSRGBColorSpace}],onChange:(t,s)=>{this.outputColorSpace=s,e()}},{type:"option",title:"Tone Mapping",value:this.toneMapping,options:[{title:"None ",value:y.NoToneMapping},{title:"Linear ",value:y.LinearToneMapping},{title:"Reinhard",value:y.ReinhardToneMapping},{title:"Cineon ",value:y.CineonToneMapping},{title:"ACES Filmic",value:y.ACESFilmicToneMapping},{title:"AgX",value:y.AgXToneMapping},{title:"Neutral",value:y.NeutralToneMapping},{title:"Custom",value:y.CustomToneMapping}],onChange:(t,s)=>{this.toneMapping=s,e()}},{type:"range",title:"Tone Mapping Exposure",value:this.toneMappingExposure,min:0,max:2,step:.01,onChange:(t,s)=>{this.toneMappingExposure=s,e()}},{type:"string",title:"Type",value:this.type,disabled:!0},{type:"button",title:"Resize Scenes from Source",onChange:()=>{this.props.three.requestSize()}}],onToggle:t=>{this.setState({expanded:t}),this.saveExpanded(t)}},Math.random())}saveExpanded(e){localStorage.setItem(this.expandedName,e?"open":"closed")}get expandedName(){return`${this.props.three.name}_renderer`}}function Jy(o){const[e]=W.useState([]),[t]=W.useState([]),[s,i]=W.useState(0),n=c=>{const h=c.value;e.push(h),t.push(E.jsx(Qn,{three:o.three,label:`Scene: ${h.name}`,scene:h,open:!1,visible:!1,onRefresh:()=>{o.three.refreshScene(h.name)},children:E.jsx(Aa,{child:h,scene:h,three:o.three})},h.name)),i(Date.now())},r=c=>{const h=c.value;for(let u=0;u<e.length;u++)if(h.uuid===e[u].uuid){e[u]=h,t[u]=E.jsx(Qn,{three:o.three,label:`Scene: ${h.name}`,scene:h,open:t[u].props.open,visible:t[u].props.visible,onRefresh:()=>{o.three.refreshScene(h.name)},children:E.jsx(Aa,{child:h,scene:h,three:o.three})},h.name),i(Date.now());return}},a=c=>{const h=c.value;for(let u=0;u<e.length;u++)if(h.uuid===e[u].uuid){e.splice(u,1),t.splice(u,1),i(Date.now());return}},l=c=>{const h=c.value.name;for(let u=0;u<e.length;u++){const d=e[u];if(d.name===h){t[u]=E.jsx(Qn,{three:o.three,label:`Scene: ${d.name}`,scene:d,open:!0,visible:!0,onRefresh:()=>{o.three.refreshScene(d.name)},children:E.jsx(Aa,{child:d,scene:d,three:o.three})},d.name);break}}i(Date.now())};return W.useEffect(()=>(o.three.addEventListener(ce.ADD_SCENE,n),o.three.addEventListener(ce.SET_SCENE,l),o.three.addEventListener(ce.REFRESH_SCENE,r),o.three.addEventListener(ce.REMOVE_SCENE,a),()=>{o.three.removeEventListener(ce.ADD_SCENE,n),o.three.removeEventListener(ce.SET_SCENE,l),o.three.removeEventListener(ce.REFRESH_SCENE,r),o.three.removeEventListener(ce.REMOVE_SCENE,a)}),[]),E.jsxs("div",{id:"SidePanel",children:[E.jsx("div",{className:"scenes",children:t},s),E.jsx(Qy,{three:o.three}),E.jsx(KN,{three:o.three}),E.jsx(Ne,{three:o.three})]})}function e0(o){return E.jsxs("div",{className:"editor",ref:o.ref,style:o.style,children:[E.jsx("div",{className:"header",children:o.header}),o.children,E.jsx("div",{className:"footer",children:o.footer})]})}function QN(o){return E.jsx(e0,{children:E.jsxs(E.Fragment,{children:[E.jsx(tt,{three:o.three,scenes:o.scenes,onSceneAdd:o.onSceneAdd,onSceneResize:o.onSceneResize,onSceneUpdate:o.onSceneUpdate}),E.jsx(Jy,{three:o.three})]})})}exports.Accordion=Qn;exports.Application=Ex;exports.BaseRemote=Kh;exports.ChildObject=Jh;exports.ContainerObject=Aa;exports.Draggable=mm;exports.DraggableItem=fm;exports.Dropdown=gm;exports.DropdownItem=ym;exports.Editor=e0;exports.ElementProxy=Mx;exports.ElementProxyReceiver=dm;exports.ExportTexture=Ni;exports.InfiniteGridHelper=Xy;exports.InfiniteGridMaterial=Yy;exports.Inspector=Qy;exports.MultiView=tt;exports.NavButton=Qh;exports.ProxyManager=Cx;exports.RemoteTheatre=Nx;exports.RemoteThree=Ix;exports.SidePanel=Jy;exports.Spline=Ga;exports.SplineEditor=Ky;exports.ThreeEditor=QN;exports.Transform=mt;exports.UVMaterial=Zy;exports.WebworkerEventHandlers=vx;exports.anchorGeometry=hm;exports.anchorGeometryTL=ix;exports.animateObjectMaterial=J0;exports.animateObjectTransform=K0;exports.applyObjectMaterial=cm;exports.capitalize=yo;exports.clamp=Si;exports.clearComposerGroups=fx;exports.colorToHex=uh;exports.copyToClipboard=sm;exports.createMask=ax;exports.cubicBezier=q0;exports.customizeTheatreElements=Z0;exports.damp=G0;exports.defaultTheatreCallback=D0;exports.detectMaxFrameRate=rm;exports.detectSettings=om;exports.dispose=Ls;exports.disposeMaterial=Xh;exports.disposeTexture=dh;exports.distance=z0;exports.generateCubemap=mx;exports.getAngle=V0;exports.getObjectMaterialObject=lm;exports.getObjectMaterialProps=am;exports.hierarchyUUID=Ha;exports.inspectComposer=px;exports.inspectComposerPass=um;exports.isColor=im;exports.map=k0;exports.mix=lr;exports.noop=go;exports.normalize=Va;exports.orthoCamera=ex;exports.parseModelLite=tx;exports.randomID=ht;exports.renderToTexture=sx;exports.resetThreeObjects=ph;exports.rgbaToHex=Y0;exports.roundTo=is;exports.setMaterialBlendAdd=hx;exports.setMaterialBlendMultiply=ux;exports.setMaterialBlendNormal=cx;exports.setMaterialBlendScreen=dx;exports.supportsOffscreenCanvas=ox;exports.triangle=ul;exports.updateCameraOrtho=nx;exports.updateCameraOrtho16x9=rx;exports.useMask=lx;exports.useStudio=X0;
|