@heliguy-xyz/splat-viewer 1.0.0-rc.26 → 1.0.0-rc.27
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/web-component/splat-viewer.esm.js +88 -19
- package/dist/web-component/splat-viewer.esm.min.js +1 -1
- package/dist/web-component/splat-viewer.js +88 -19
- package/dist/web-component/splat-viewer.min.js +1 -1
- package/dist/web-component/supersplat-core/controllers.d.ts +5 -0
- package/dist/web-component/supersplat-core/controllers.d.ts.map +1 -1
- package/dist/web-component/supersplat-core/splat.d.ts.map +1 -1
- package/dist/web-component/types/supersplat-core/controllers.d.ts +5 -0
- package/dist/web-component/types/supersplat-core/controllers.d.ts.map +1 -1
- package/dist/web-component/types/supersplat-core/splat.d.ts.map +1 -1
- package/dist/web-component/types/web-component/OrbitCameraScript.d.ts.map +1 -1
- package/dist/web-component/types/web-component/SplatViewerCore.d.ts.map +1 -1
- package/dist/web-component/types/web-component/SupersplatAdapter.d.ts +9 -0
- package/dist/web-component/types/web-component/SupersplatAdapter.d.ts.map +1 -1
- package/dist/web-component/types/web-component/utils/config.d.ts +1 -0
- package/dist/web-component/types/web-component/utils/config.d.ts.map +1 -1
- package/dist/web-component/web-component/OrbitCameraScript.d.ts.map +1 -1
- package/dist/web-component/web-component/SplatViewerCore.d.ts.map +1 -1
- package/dist/web-component/web-component/SupersplatAdapter.d.ts +9 -0
- package/dist/web-component/web-component/SupersplatAdapter.d.ts.map +1 -1
- package/dist/web-component/web-component/utils/config.d.ts +1 -0
- package/dist/web-component/web-component/utils/config.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2010-2023 Three.js Authors
|
|
5
5
|
* SPDX-License-Identifier: MIT
|
|
6
|
-
*/const pD="157",fD=0,mD=1,_D=2,gD=100,vD=101,yD=102,SD=200,xD=201,TD=202,ED=203,bD=204,wD=205,AD=206,CD=207,MD=208,PD=209,RD=210,LD=301,DD=302,ID=306,OD=1e3,ND=1001,FD=1002,UD=1003,BD=1004,zD=1005,kD=1006,VD=1007,HD=1008,GD=1009,WD=1012,XD=1013,YD=1014,qD=1015,jD=1016,$D=1020,KD=1023,ZD=1026,QD=1027,JD=33776,tI=33777,eI=33778,iI=33779,sI=36492,nI=3001,rI="",aI="srgb",oI="srgb-linear",lI="display-p3",hI="display-p3-linear",cI="linear",dI="srgb",uI="rec709",pI="p3",fI=7680,mI=512,_I=513,gI=514,vI=515,yI=516,SI=517,xI=518,TI=519,EI="300 es",bI=1035,wI=2e3,AI=2001;class CI{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const i=this._listeners;return void 0!==i[t]&&-1!==i[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const i=this._listeners[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const i=e.slice(0);for(let e=0,s=i.length;e<s;e++)i[e].call(this,t);t.target=null}}}const MI=["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"],PI=Math.PI/180,RI=180/Math.PI;function LI(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(MI[255&t]+MI[t>>8&255]+MI[t>>16&255]+MI[t>>24&255]+"-"+MI[255&e]+MI[e>>8&255]+"-"+MI[e>>16&15|64]+MI[e>>24&255]+"-"+MI[63&i|128]+MI[i>>8&255]+"-"+MI[i>>16&255]+MI[i>>24&255]+MI[255&s]+MI[s>>8&255]+MI[s>>16&255]+MI[s>>24&255]).toLowerCase()}function DI(t,e,i){return Math.max(e,Math.min(i,t))}function II(t,e,i){return(1-i)*t+i*e}function OI(t){return!(t&t-1)&&0!==t}function NI(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function FI(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function UI(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}class BI{constructor(t=0,e=0){BI.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(DI(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class zI{constructor(t,e,i,s,n,r,a,o,l){zI.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,a,o,l)}set(t,e,i,s,n,r,a,o,l){const h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=n,h[5]=o,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[3],o=i[6],l=i[1],h=i[4],c=i[7],d=i[2],u=i[5],p=i[8],f=s[0],m=s[3],_=s[6],g=s[1],v=s[4],y=s[7],S=s[2],x=s[5],T=s[8];return n[0]=r*f+a*g+o*S,n[3]=r*m+a*v+o*x,n[6]=r*_+a*y+o*T,n[1]=l*f+h*g+c*S,n[4]=l*m+h*v+c*x,n[7]=l*_+h*y+c*T,n[2]=d*f+u*g+p*S,n[5]=d*m+u*v+p*x,n[8]=d*_+u*y+p*T,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*n*h+i*a*o+s*n*l-s*r*o}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8],c=h*r-a*l,d=a*o-h*n,u=l*n-r*o,p=e*c+i*d+s*u;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return t[0]=c*f,t[1]=(s*l-h*i)*f,t[2]=(a*i-s*r)*f,t[3]=d*f,t[4]=(h*e-s*o)*f,t[5]=(s*n-a*e)*f,t[6]=u*f,t[7]=(i*o-l*e)*f,t[8]=(r*e-i*n)*f,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,n,r,a){const o=Math.cos(n),l=Math.sin(n);return this.set(i*o,i*l,-i*(o*r+l*a)+r+t,-s*l,s*o,-s*(-l*r+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(kI.makeScale(t,e)),this}rotate(t){return this.premultiply(kI.makeRotation(-t)),this}translate(t,e){return this.premultiply(kI.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const kI=new zI;function VI(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function HI(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function GI(){const t=HI("canvas");return t.style.display="block",t}const WI={};function XI(t){t in WI||(WI[t]=!0)}const YI=(new zI).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),qI=(new zI).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),jI={[oI]:{transfer:cI,primaries:uI,toReference:t=>t,fromReference:t=>t},[aI]:{transfer:dI,primaries:uI,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[hI]:{transfer:cI,primaries:pI,toReference:t=>t.applyMatrix3(qI),fromReference:t=>t.applyMatrix3(YI)},[lI]:{transfer:dI,primaries:pI,toReference:t=>t.convertSRGBToLinear().applyMatrix3(qI),fromReference:t=>t.applyMatrix3(YI).convertLinearToSRGB()}},$I=new Set([oI,hI]),KI={enabled:!0,_workingColorSpace:oI,get legacyMode(){return!this.enabled},set legacyMode(t){this.enabled=!t},get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!$I.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,i){if(!1===this.enabled||e===i||!e||!i)return t;const s=jI[e].toReference;return(0,jI[i].fromReference)(s(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return jI[t].primaries},getTransfer:function(t){return t===rI?cI:jI[t].transfer}};function ZI(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function QI(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let JI;class tO{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===JI&&(JI=HI("canvas")),JI.width=t.width,JI.height=t.height;const i=JI.getContext("2d");t instanceof ImageData?i.putImageData(t,0,0):i.drawImage(t,0,0,t.width,t.height),e=JI}return e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=HI("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),n=s.data;for(let t=0;t<n.length;t++)n[t]=255*ZI(n[t]/255);return i.putImageData(s,0,0),e}if(t.data){const e=t.data.slice(0);for(let t=0;t<e.length;t++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[t]=Math.floor(255*ZI(e[t]/255)):e[t]=ZI(e[t]);return{data:e,width:t.width,height:t.height}}return t}}let eO=0;class iO{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:eO++}),this.uuid=LI(),this.data=t,this.version=0}set needsUpdate(t){!0===t&&this.version++}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.images[this.uuid])return t.images[this.uuid];const i={uuid:this.uuid,url:""},s=this.data;if(null!==s){let t;if(Array.isArray(s)){t=[];for(let e=0,i=s.length;e<i;e++)s[e].isDataTexture?t.push(sO(s[e].image)):t.push(sO(s[e]))}else t=sO(s);i.url=t}return e||(t.images[this.uuid]=i),i}}function sO(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?tO.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:{}}let nO=0;class rO extends CI{constructor(t=rO.DEFAULT_IMAGE,e=rO.DEFAULT_MAPPING,i=1001,s=1001,n=1006,r=1008,a=1023,o=1009,l=rO.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nO++}),this.uuid=LI(),this.name="",this.source=new iO(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=s,this.magFilter=n,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new BI(0,0),this.repeat=new BI(1,1),this.center=new BI(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new zI,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,"string"==typeof h?this.colorSpace=h:(XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===nI?aI:rI),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).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&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(300!==this.mapping)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case OD:t.x=t.x-Math.floor(t.x);break;case ND:t.x=t.x<0?0:1;break;case FD:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case OD:t.y=t.y-Math.floor(t.y);break;case ND:t.y=t.y<0?0:1;break;case FD:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===aI?nI:3e3}set encoding(t){XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=t===nI?aI:rI}}rO.DEFAULT_IMAGE=null,rO.DEFAULT_MAPPING=300,rO.DEFAULT_ANISOTROPY=1;class aO{constructor(t=0,e=0,i=0,s=1){aO.prototype.isVector4=!0,this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){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: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,n;const r=.01,a=.1,o=t.elements,l=o[0],h=o[4],c=o[8],d=o[1],u=o[5],p=o[9],f=o[2],m=o[6],_=o[10];if(Math.abs(h-d)<r&&Math.abs(c-f)<r&&Math.abs(p-m)<r){if(Math.abs(h+d)<a&&Math.abs(c+f)<a&&Math.abs(p+m)<a&&Math.abs(l+u+_-3)<a)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,o=(u+1)/2,g=(_+1)/2,v=(h+d)/4,y=(c+f)/4,S=(p+m)/4;return t>o&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=y/i):o>g?o<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(o),i=v/s,n=S/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=y/n,s=S/n),this.set(i,s,n,e),this}let g=Math.sqrt((m-p)*(m-p)+(c-f)*(c-f)+(d-h)*(d-h));return Math.abs(g)<.001&&(g=1),this.x=(m-p)/g,this.y=(c-f)/g,this.z=(d-h)/g,this.w=Math.acos((l+u+_-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),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}}class oO extends CI{constructor(t=1,e=1,i={}){super(),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=1,this.scissor=new aO(0,0,t,e),this.scissorTest=!1,this.viewport=new aO(0,0,t,e);const s={width:t,height:e,depth:1};void 0!==i.encoding&&(XI("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),i.colorSpace=i.encoding===nI?aI:rI),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:kD,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},i),this.texture=new rO(s,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=i.generateMipmaps,this.texture.internalFormat=i.internalFormat,this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}setSize(t,e,i=1){this.width===t&&this.height===e&&this.depth===i||(this.width=t,this.height=e,this.depth=i,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=i,this.dispose()),this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return(new this.constructor).copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.isRenderTargetTexture=!0;const e=Object.assign({},t.texture.image);return this.texture.source=new iO(e),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,null!==t.depthTexture&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class lO extends oO{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class hO extends rO{constructor(t=null,e=1,i=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:s},this.magFilter=UD,this.minFilter=UD,this.wrapR=ND,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class cO extends rO{constructor(t=null,e=1,i=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:s},this.magFilter=UD,this.minFilter=UD,this.wrapR=ND,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class dO{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,a){let o=i[s+0],l=i[s+1],h=i[s+2],c=i[s+3];const d=n[r+0],u=n[r+1],p=n[r+2],f=n[r+3];if(0===a)return t[e+0]=o,t[e+1]=l,t[e+2]=h,void(t[e+3]=c);if(1===a)return t[e+0]=d,t[e+1]=u,t[e+2]=p,void(t[e+3]=f);if(c!==f||o!==d||l!==u||h!==p){let t=1-a;const e=o*d+l*u+h*p+c*f,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,a=Math.sin(a*r)/n}const n=a*i;if(o=o*t+d*n,l=l*t+u*n,h=h*t+p*n,c=c*t+f*n,t===1-a){const t=1/Math.sqrt(o*o+l*l+h*h+c*c);o*=t,l*=t,h*=t,c*=t}}t[e]=o,t[e+1]=l,t[e+2]=h,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,n,r){const a=i[s],o=i[s+1],l=i[s+2],h=i[s+3],c=n[r],d=n[r+1],u=n[r+2],p=n[r+3];return t[e]=a*p+h*c+o*u-l*d,t[e+1]=o*p+h*d+l*c-a*u,t[e+2]=l*p+h*u+a*d-o*c,t[e+3]=h*p-a*c-o*d-l*u,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e){const i=t._x,s=t._y,n=t._z,r=t._order,a=Math.cos,o=Math.sin,l=a(i/2),h=a(s/2),c=a(n/2),d=o(i/2),u=o(s/2),p=o(n/2);switch(r){case"XYZ":this._x=d*h*c+l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c-d*u*p;break;case"YXZ":this._x=d*h*c+l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c+d*u*p;break;case"ZXY":this._x=d*h*c-l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c-d*u*p;break;case"ZYX":this._x=d*h*c-l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c+d*u*p;break;case"YZX":this._x=d*h*c+l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c-d*u*p;break;case"XZY":this._x=d*h*c-l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c+d*u*p}return!1!==e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],a=e[5],o=e[9],l=e[2],h=e[6],c=e[10],d=i+a+c;if(d>0){const t=.5/Math.sqrt(d+1);this._w=.25/t,this._x=(h-o)*t,this._y=(n-l)*t,this._z=(r-s)*t}else if(i>a&&i>c){const t=2*Math.sqrt(1+i-a-c);this._w=(h-o)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+l)/t}else if(a>c){const t=2*Math.sqrt(1+a-i-c);this._w=(n-l)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(o+h)/t}else{const t=2*Math.sqrt(1+c-i-a);this._w=(r-s)/t,this._x=(n+l)/t,this._y=(o+h)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(DI(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,n=t._z,r=t._w,a=e._x,o=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+s*l-n*o,this._y=s*h+r*o+n*a-i*l,this._z=n*h+r*l+i*o-s*a,this._w=r*h-i*a-s*o-n*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let a=r*t._w+i*t._x+s*t._y+n*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=r,this._x=i,this._y=s,this._z=n,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*n+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),h=Math.atan2(l,a),c=Math.sin((1-e)*h)/l,d=Math.sin(e*h)/l;return this._w=r*c+this._w*d,this._x=i*c+this._x*d,this._y=s*c+this._y*d,this._z=n*c+this._z*d,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=Math.random(),e=Math.sqrt(1-t),i=Math.sqrt(t),s=2*Math.PI*Math.random(),n=2*Math.PI*Math.random();return this.set(e*Math.cos(s),i*Math.sin(n),i*Math.cos(n),e*Math.sin(s))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class uO{constructor(t=0,e=0,i=0){uO.prototype.isVector3=!0,this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(fO.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(fO.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,a=t.z,o=t.w,l=o*e+r*s-a*i,h=o*i+a*e-n*s,c=o*s+n*i-r*e,d=-n*e-r*i-a*s;return this.x=l*o+d*-n+h*-a-c*-r,this.y=h*o+d*-r+c*-n-l*-a,this.z=c*o+d*-a+l*-r-h*-n,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,a=e.y,o=e.z;return this.x=s*o-n*a,this.y=n*r-i*o,this.z=i*a-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return pO.copy(this).projectOnVector(t),this.sub(pO)}reflect(t){return this.sub(pO.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(DI(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=2*(Math.random()-.5),e=Math.random()*Math.PI*2,i=Math.sqrt(1-t**2);return this.x=i*Math.cos(e),this.y=i*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pO=new uO,fO=new dO;class mO{constructor(t=new uO(1/0,1/0,1/0),e=new uO(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(gO.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(gO.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=gO.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.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(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){if(t.updateWorldMatrix(!1,!1),void 0!==t.boundingBox)null===t.boundingBox&&t.computeBoundingBox(),vO.copy(t.boundingBox),vO.applyMatrix4(t.matrixWorld),this.union(vO);else{const i=t.geometry;if(void 0!==i)if(e&&void 0!==i.attributes&&void 0!==i.attributes.position){const e=i.attributes.position;for(let i=0,s=e.count;i<s;i++)gO.fromBufferAttribute(e,i).applyMatrix4(t.matrixWorld),this.expandByPoint(gO)}else null===i.boundingBox&&i.computeBoundingBox(),vO.copy(i.boundingBox),vO.applyMatrix4(t.matrixWorld),this.union(vO)}const i=t.children;for(let t=0,s=i.length;t<s;t++)this.expandByObject(i[t],e);return this}containsPoint(t){return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y||t.z<this.min.z||t.z>this.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y||t.max.z<this.min.z||t.min.z>this.max.z)}intersectsSphere(t){return this.clampPoint(t.center,gO),gO.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(wO),AO.subVectors(this.max,wO),yO.subVectors(t.a,wO),SO.subVectors(t.b,wO),xO.subVectors(t.c,wO),TO.subVectors(SO,yO),EO.subVectors(xO,SO),bO.subVectors(yO,xO);let e=[0,-TO.z,TO.y,0,-EO.z,EO.y,0,-bO.z,bO.y,TO.z,0,-TO.x,EO.z,0,-EO.x,bO.z,0,-bO.x,-TO.y,TO.x,0,-EO.y,EO.x,0,-bO.y,bO.x,0];return!!PO(e,yO,SO,xO,AO)&&(e=[1,0,0,0,1,0,0,0,1],!!PO(e,yO,SO,xO,AO)&&(CO.crossVectors(TO,EO),e=[CO.x,CO.y,CO.z],PO(e,yO,SO,xO,AO)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,gO).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(gO).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(_O[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),_O[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),_O[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),_O[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),_O[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),_O[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),_O[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),_O[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(_O)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const _O=[new uO,new uO,new uO,new uO,new uO,new uO,new uO,new uO],gO=new uO,vO=new mO,yO=new uO,SO=new uO,xO=new uO,TO=new uO,EO=new uO,bO=new uO,wO=new uO,AO=new uO,CO=new uO,MO=new uO;function PO(t,e,i,s,n){for(let r=0,a=t.length-3;r<=a;r+=3){MO.fromArray(t,r);const a=n.x*Math.abs(MO.x)+n.y*Math.abs(MO.y)+n.z*Math.abs(MO.z),o=e.dot(MO),l=i.dot(MO),h=s.dot(MO);if(Math.max(-Math.max(o,l,h),Math.min(o,l,h))>a)return!1}return!0}const RO=new mO,LO=new uO,DO=new uO;class IO{constructor(t=new uO,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;void 0!==e?i.copy(e):RO.setFromPoints(t).getCenter(i);let s=0;for(let e=0,n=t.length;e<n;e++)s=Math.max(s,i.distanceToSquared(t[e]));return this.radius=Math.sqrt(s),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;LO.subVectors(t,this.center);const e=LO.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(LO,i/t),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(DO.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(LO.copy(t.center).add(DO)),this.expandByPoint(LO.copy(t.center).sub(DO))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const OO=new uO,NO=new uO,FO=new uO,UO=new uO,BO=new uO,zO=new uO,kO=new uO;class VO{constructor(t=new uO,e=new uO(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,OO)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=OO.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(OO.copy(this.origin).addScaledVector(this.direction,e),OO.distanceToSquared(t))}distanceSqToSegment(t,e,i,s){NO.copy(t).add(e).multiplyScalar(.5),FO.copy(e).sub(t).normalize(),UO.copy(this.origin).sub(NO);const n=.5*t.distanceTo(e),r=-this.direction.dot(FO),a=UO.dot(this.direction),o=-UO.dot(FO),l=UO.lengthSq(),h=Math.abs(1-r*r);let c,d,u,p;if(h>0)if(c=r*o-a,d=r*a-o,p=n*h,c>=0)if(d>=-p)if(d<=p){const t=1/h;c*=t,d*=t,u=c*(c+r*d+2*a)+d*(r*c+d+2*o)+l}else d=n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;else d=-n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;else d<=-p?(c=Math.max(0,-(-r*n+a)),d=c>0?-n:Math.min(Math.max(-n,-o),n),u=-c*c+d*(d+2*o)+l):d<=p?(c=0,d=Math.min(Math.max(-n,-o),n),u=d*(d+2*o)+l):(c=Math.max(0,-(r*n+a)),d=c>0?n:Math.min(Math.max(-n,-o),n),u=-c*c+d*(d+2*o)+l);else d=r>0?-n:n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,c),s&&s.copy(NO).addScaledVector(FO,d),u}intersectSphere(t,e){OO.subVectors(t.center,this.origin);const i=OO.dot(this.direction),s=OO.dot(OO)-i*i,n=t.radius*t.radius;if(s>n)return null;const r=Math.sqrt(n-s),a=i-r,o=i+r;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return null===i?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,s,n,r,a,o;const l=1/this.direction.x,h=1/this.direction.y,c=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,s=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,s=(t.min.x-d.x)*l),h>=0?(n=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(n=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||n>s?null:((n>i||isNaN(i))&&(i=n),(r<s||isNaN(s))&&(s=r),c>=0?(a=(t.min.z-d.z)*c,o=(t.max.z-d.z)*c):(a=(t.max.z-d.z)*c,o=(t.min.z-d.z)*c),i>o||a>s?null:((a>i||i!=i)&&(i=a),(o<s||s!=s)&&(s=o),s<0?null:this.at(i>=0?i:s,e)))}intersectsBox(t){return null!==this.intersectBox(t,OO)}intersectTriangle(t,e,i,s,n){BO.subVectors(e,t),zO.subVectors(i,t),kO.crossVectors(BO,zO);let r,a=this.direction.dot(kO);if(a>0){if(s)return null;r=1}else{if(!(a<0))return null;r=-1,a=-a}UO.subVectors(this.origin,t);const o=r*this.direction.dot(zO.crossVectors(UO,zO));if(o<0)return null;const l=r*this.direction.dot(BO.cross(UO));if(l<0)return null;if(o+l>a)return null;const h=-r*UO.dot(kO);return h<0?null:this.at(h/a,n)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class HO{constructor(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m){HO.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m)}set(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m){const _=this.elements;return _[0]=t,_[4]=e,_[8]=i,_[12]=s,_[1]=n,_[5]=r,_[9]=a,_[13]=o,_[2]=l,_[6]=h,_[10]=c,_[14]=d,_[3]=u,_[7]=p,_[11]=f,_[15]=m,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 HO).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/GO.setFromMatrixColumn(t,0).length(),n=1/GO.setFromMatrixColumn(t,1).length(),r=1/GO.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),a=Math.sin(i),o=Math.cos(s),l=Math.sin(s),h=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*h,i=r*c,s=a*h,n=a*c;e[0]=o*h,e[4]=-o*c,e[8]=l,e[1]=i+s*l,e[5]=t-n*l,e[9]=-a*o,e[2]=n-t*l,e[6]=s+i*l,e[10]=r*o}else if("YXZ"===t.order){const t=o*h,i=o*c,s=l*h,n=l*c;e[0]=t+n*a,e[4]=s*a-i,e[8]=r*l,e[1]=r*c,e[5]=r*h,e[9]=-a,e[2]=i*a-s,e[6]=n+t*a,e[10]=r*o}else if("ZXY"===t.order){const t=o*h,i=o*c,s=l*h,n=l*c;e[0]=t-n*a,e[4]=-r*c,e[8]=s+i*a,e[1]=i+s*a,e[5]=r*h,e[9]=n-t*a,e[2]=-r*l,e[6]=a,e[10]=r*o}else if("ZYX"===t.order){const t=r*h,i=r*c,s=a*h,n=a*c;e[0]=o*h,e[4]=s*l-i,e[8]=t*l+n,e[1]=o*c,e[5]=n*l+t,e[9]=i*l-s,e[2]=-l,e[6]=a*o,e[10]=r*o}else if("YZX"===t.order){const t=r*o,i=r*l,s=a*o,n=a*l;e[0]=o*h,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*o,i=r*l,s=a*o,n=a*l;e[0]=o*h,e[4]=-c,e[8]=l*h,e[1]=t*c+n,e[5]=r*h,e[9]=i*c-s,e[2]=s*c-i,e[6]=a*h,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(XO,t,YO)}lookAt(t,e,i){const s=this.elements;return $O.subVectors(t,e),0===$O.lengthSq()&&($O.z=1),$O.normalize(),qO.crossVectors(i,$O),0===qO.lengthSq()&&(1===Math.abs(i.z)?$O.x+=1e-4:$O.z+=1e-4,$O.normalize(),qO.crossVectors(i,$O)),qO.normalize(),jO.crossVectors($O,qO),s[0]=qO.x,s[4]=jO.x,s[8]=$O.x,s[1]=qO.y,s[5]=jO.y,s[9]=$O.y,s[2]=qO.z,s[6]=jO.z,s[10]=$O.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[4],o=i[8],l=i[12],h=i[1],c=i[5],d=i[9],u=i[13],p=i[2],f=i[6],m=i[10],_=i[14],g=i[3],v=i[7],y=i[11],S=i[15],x=s[0],T=s[4],E=s[8],b=s[12],w=s[1],A=s[5],C=s[9],M=s[13],P=s[2],R=s[6],L=s[10],D=s[14],I=s[3],O=s[7],N=s[11],F=s[15];return n[0]=r*x+a*w+o*P+l*I,n[4]=r*T+a*A+o*R+l*O,n[8]=r*E+a*C+o*L+l*N,n[12]=r*b+a*M+o*D+l*F,n[1]=h*x+c*w+d*P+u*I,n[5]=h*T+c*A+d*R+u*O,n[9]=h*E+c*C+d*L+u*N,n[13]=h*b+c*M+d*D+u*F,n[2]=p*x+f*w+m*P+_*I,n[6]=p*T+f*A+m*R+_*O,n[10]=p*E+f*C+m*L+_*N,n[14]=p*b+f*M+m*D+_*F,n[3]=g*x+v*w+y*P+S*I,n[7]=g*T+v*A+y*R+S*O,n[11]=g*E+v*C+y*L+S*N,n[15]=g*b+v*M+y*D+S*F,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[12],r=t[1],a=t[5],o=t[9],l=t[13],h=t[2],c=t[6],d=t[10],u=t[14];return t[3]*(+n*o*c-s*l*c-n*a*d+i*l*d+s*a*u-i*o*u)+t[7]*(+e*o*u-e*l*d+n*r*d-s*r*u+s*l*h-n*o*h)+t[11]*(+e*l*c-e*a*u-n*r*c+i*r*u+n*a*h-i*l*h)+t[15]*(-s*a*h-e*o*c+e*a*d+s*r*c-i*r*d+i*o*h)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8],c=t[9],d=t[10],u=t[11],p=t[12],f=t[13],m=t[14],_=t[15],g=c*m*l-f*d*l+f*o*u-a*m*u-c*o*_+a*d*_,v=p*d*l-h*m*l-p*o*u+r*m*u+h*o*_-r*d*_,y=h*f*l-p*c*l+p*a*u-r*f*u-h*a*_+r*c*_,S=p*c*o-h*f*o-p*a*d+r*f*d+h*a*m-r*c*m,x=e*g+i*v+s*y+n*S;if(0===x)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/x;return t[0]=g*T,t[1]=(f*d*n-c*m*n-f*s*u+i*m*u+c*s*_-i*d*_)*T,t[2]=(a*m*n-f*o*n+f*s*l-i*m*l-a*s*_+i*o*_)*T,t[3]=(c*o*n-a*d*n-c*s*l+i*d*l+a*s*u-i*o*u)*T,t[4]=v*T,t[5]=(h*m*n-p*d*n+p*s*u-e*m*u-h*s*_+e*d*_)*T,t[6]=(p*o*n-r*m*n-p*s*l+e*m*l+r*s*_-e*o*_)*T,t[7]=(r*d*n-h*o*n+h*s*l-e*d*l-r*s*u+e*o*u)*T,t[8]=y*T,t[9]=(p*c*n-h*f*n-p*i*u+e*f*u+h*i*_-e*c*_)*T,t[10]=(r*f*n-p*a*n+p*i*l-e*f*l-r*i*_+e*a*_)*T,t[11]=(h*a*n-r*c*n-h*i*l+e*c*l+r*i*u-e*a*u)*T,t[12]=S*T,t[13]=(h*f*s-p*c*s+p*i*d-e*f*d-h*i*m+e*c*m)*T,t[14]=(p*a*s-r*f*s-p*i*o+e*f*o+r*i*m-e*a*m)*T,t[15]=(r*c*s-h*a*s+h*i*o-e*c*o-r*i*d+e*a*d)*T,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,a=t.y,o=t.z,l=n*r,h=n*a;return this.set(l*r+i,l*a-s*o,l*o+s*a,0,l*a+s*o,h*a+i,h*o-s*r,0,l*o-s*a,h*o+s*r,n*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,a=e._z,o=e._w,l=n+n,h=r+r,c=a+a,d=n*l,u=n*h,p=n*c,f=r*h,m=r*c,_=a*c,g=o*l,v=o*h,y=o*c,S=i.x,x=i.y,T=i.z;return s[0]=(1-(f+_))*S,s[1]=(u+y)*S,s[2]=(p-v)*S,s[3]=0,s[4]=(u-y)*x,s[5]=(1-(d+_))*x,s[6]=(m+g)*x,s[7]=0,s[8]=(p+v)*T,s[9]=(m-g)*T,s[10]=(1-(d+f))*T,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=GO.set(s[0],s[1],s[2]).length();const r=GO.set(s[4],s[5],s[6]).length(),a=GO.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],WO.copy(this);const o=1/n,l=1/r,h=1/a;return WO.elements[0]*=o,WO.elements[1]*=o,WO.elements[2]*=o,WO.elements[4]*=l,WO.elements[5]*=l,WO.elements[6]*=l,WO.elements[8]*=h,WO.elements[9]*=h,WO.elements[10]*=h,e.setFromRotationMatrix(WO),i.x=n,i.y=r,i.z=a,this}makePerspective(t,e,i,s,n,r,a=2e3){const o=this.elements,l=2*n/(e-t),h=2*n/(i-s),c=(e+t)/(e-t),d=(i+s)/(i-s);let u,p;if(a===wI)u=-(r+n)/(r-n),p=-2*r*n/(r-n);else{if(a!==AI)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);u=-r/(r-n),p=-r*n/(r-n)}return o[0]=l,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=h,o[9]=d,o[13]=0,o[2]=0,o[6]=0,o[10]=u,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,i,s,n,r,a=2e3){const o=this.elements,l=1/(e-t),h=1/(i-s),c=1/(r-n),d=(e+t)*l,u=(i+s)*h;let p,f;if(a===wI)p=(r+n)*c,f=-2*c;else{if(a!==AI)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=n*c,f=-1*c}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-d,o[1]=0,o[5]=2*h,o[9]=0,o[13]=-u,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const GO=new uO,WO=new HO,XO=new uO(0,0,0),YO=new uO(1,1,1),qO=new uO,jO=new uO,$O=new uO,KO=new HO,ZO=new dO;class QO{constructor(t=0,e=0,i=0,s=QO.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,n=s[0],r=s[4],a=s[8],o=s[1],l=s[5],h=s[9],c=s[2],d=s[6],u=s[10];switch(e){case"XYZ":this._y=Math.asin(DI(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,u),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-DI(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,u),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(DI(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-c,u),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(o,n));break;case"ZYX":this._y=Math.asin(-DI(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(d,u),this._z=Math.atan2(o,n)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(DI(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(a,u));break;case"XZY":this._z=Math.asin(-DI(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-h,u),this._y=0)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return KO.makeRotationFromQuaternion(t),this.setFromRotationMatrix(KO,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return ZO.setFromEuler(this),this.setFromQuaternion(ZO,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}QO.DEFAULT_ORDER="XYZ";class JO{constructor(){this.mask=1}set(t){this.mask=1<<t>>>0}enable(t){this.mask|=1<<t}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t}disable(t){this.mask&=~(1<<t)}disableAll(){this.mask=0}test(t){return 0!==(this.mask&t.mask)}isEnabled(t){return!!(this.mask&1<<t)}}let tN=0;const eN=new uO,iN=new dO,sN=new HO,nN=new uO,rN=new uO,aN=new uO,oN=new dO,lN=new uO(1,0,0),hN=new uO(0,1,0),cN=new uO(0,0,1),dN={type:"added"},uN={type:"removed"};class pN extends CI{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:tN++}),this.uuid=LI(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=pN.DEFAULT_UP.clone();const t=new uO,e=new QO,i=new dO,s=new uO(1,1,1);e._onChange(function(){i.setFromEuler(e,!1)}),i._onChange(function(){e.setFromQuaternion(i,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new HO},normalMatrix:{value:new zI}}),this.matrix=new HO,this.matrixWorld=new HO,this.matrixAutoUpdate=pN.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.matrixWorldAutoUpdate=pN.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.layers=new JO,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return iN.setFromAxisAngle(t,e),this.quaternion.multiply(iN),this}rotateOnWorldAxis(t,e){return iN.setFromAxisAngle(t,e),this.quaternion.premultiply(iN),this}rotateX(t){return this.rotateOnAxis(lN,t)}rotateY(t){return this.rotateOnAxis(hN,t)}rotateZ(t){return this.rotateOnAxis(cN,t)}translateOnAxis(t,e){return eN.copy(t).applyQuaternion(this.quaternion),this.position.add(eN.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(lN,t)}translateY(t){return this.translateOnAxis(hN,t)}translateZ(t){return this.translateOnAxis(cN,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(sN.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?nN.copy(t):nN.set(t,e,i);const s=this.parent;this.updateWorldMatrix(!0,!1),rN.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?sN.lookAt(rN,nN,this.up):sN.lookAt(nN,rN,this.up),this.quaternion.setFromRotationMatrix(sN),s&&(sN.extractRotation(s.matrixWorld),iN.setFromRotationMatrix(sN),this.quaternion.premultiply(iN.invert()))}add(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return t===this||t&&t.isObject3D&&(null!==t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t),t.dispatchEvent(dN)),this}remove(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.remove(arguments[t]);return this}const e=this.children.indexOf(t);return-1!==e&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(uN)),this}removeFromParent(){const t=this.parent;return null!==t&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),sN.copy(this.matrixWorld).invert(),null!==t.parent&&(t.parent.updateWorldMatrix(!0,!1),sN.multiply(t.parent.matrixWorld)),t.applyMatrix4(sN),this.add(t),t.updateWorldMatrix(!1,!0),this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,s=this.children.length;i<s;i++){const s=this.children[i].getObjectByProperty(t,e);if(void 0!==s)return s}}getObjectsByProperty(t,e){let i=[];this[t]===e&&i.push(this);for(let s=0,n=this.children.length;s<n;s++){const n=this.children[s].getObjectsByProperty(t,e);n.length>0&&(i=i.concat(n))}return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rN,t,aN),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rN,oN,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverse(t)}traverseVisible(t){if(!1===this.visible)return;t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;null!==e&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,s=e.length;i<s;i++){const s=e[i];!0!==s.matrixWorldAutoUpdate&&!0!==t||s.updateMatrixWorld(t)}}updateWorldMatrix(t,e){const i=this.parent;if(!0===t&&null!==i&&!0===i.matrixWorldAutoUpdate&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),!0===e){const t=this.children;for(let e=0,i=t.length;e<i;e++){const i=t[e];!0===i.matrixWorldAutoUpdate&&i.updateWorldMatrix(!1,!0)}}}toJSON(t){const e=void 0===t||"string"==typeof t,i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const s={};function n(e,i){return void 0===e[i.uuid]&&(e[i.uuid]=i.toJSON(t)),i.uuid}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),!0===this.castShadow&&(s.castShadow=!0),!0===this.receiveShadow&&(s.receiveShadow=!0),!1===this.visible&&(s.visible=!1),!1===this.frustumCulled&&(s.frustumCulled=!1),0!==this.renderOrder&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(s.instanceColor=this.instanceColor.toJSON())),this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=n(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const i=e.shapes;if(Array.isArray(i))for(let e=0,s=i.length;e<s;e++){const s=i[e];n(t.shapes,s)}else n(t.shapes,i)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(n(t.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const e=[];for(let i=0,s=this.material.length;i<s;i++)e.push(n(t.materials,this.material[i]));s.material=e}else s.material=n(t.materials,this.material);if(this.children.length>0){s.children=[];for(let e=0;e<this.children.length;e++)s.children.push(this.children[e].toJSON(t).object)}if(this.animations.length>0){s.animations=[];for(let e=0;e<this.animations.length;e++){const i=this.animations[e];s.animations.push(n(t.animations,i))}}if(e){const e=r(t.geometries),s=r(t.materials),n=r(t.textures),a=r(t.images),o=r(t.shapes),l=r(t.skeletons),h=r(t.animations),c=r(t.nodes);e.length>0&&(i.geometries=e),s.length>0&&(i.materials=s),n.length>0&&(i.textures=n),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),h.length>0&&(i.animations=h),c.length>0&&(i.nodes=c)}return i.object=s,i;function r(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e<t.children.length;e++){const i=t.children[e];this.add(i.clone())}return this}}pN.DEFAULT_UP=new uO(0,1,0),pN.DEFAULT_MATRIX_AUTO_UPDATE=!0,pN.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const fN=new uO,mN=new uO,_N=new uO,gN=new uO,vN=new uO,yN=new uO,SN=new uO,xN=new uO,TN=new uO,EN=new uO;let bN=!1;class wN{constructor(t=new uO,e=new uO,i=new uO){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,s){s.subVectors(i,e),fN.subVectors(t,e),s.cross(fN);const n=s.lengthSq();return n>0?s.multiplyScalar(1/Math.sqrt(n)):s.set(0,0,0)}static getBarycoord(t,e,i,s,n){fN.subVectors(s,e),mN.subVectors(i,e),_N.subVectors(t,e);const r=fN.dot(fN),a=fN.dot(mN),o=fN.dot(_N),l=mN.dot(mN),h=mN.dot(_N),c=r*l-a*a;if(0===c)return n.set(-2,-1,-1);const d=1/c,u=(l*o-a*h)*d,p=(r*h-a*o)*d;return n.set(1-u-p,p,u)}static containsPoint(t,e,i,s){return this.getBarycoord(t,e,i,s,gN),gN.x>=0&&gN.y>=0&&gN.x+gN.y<=1}static getUV(t,e,i,s,n,r,a,o){return!1===bN&&(bN=!0),this.getInterpolation(t,e,i,s,n,r,a,o)}static getInterpolation(t,e,i,s,n,r,a,o){return this.getBarycoord(t,e,i,s,gN),o.setScalar(0),o.addScaledVector(n,gN.x),o.addScaledVector(r,gN.y),o.addScaledVector(a,gN.z),o}static isFrontFacing(t,e,i,s){return fN.subVectors(i,e),mN.subVectors(t,e),fN.cross(mN).dot(s)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,s){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,i,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,s),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return fN.subVectors(this.c,this.b),mN.subVectors(this.a,this.b),.5*fN.cross(mN).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return wN.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return wN.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,i,s,n){return!1===bN&&(bN=!0),wN.getInterpolation(t,this.a,this.b,this.c,e,i,s,n)}getInterpolation(t,e,i,s,n){return wN.getInterpolation(t,this.a,this.b,this.c,e,i,s,n)}containsPoint(t){return wN.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return wN.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,s=this.b,n=this.c;let r,a;vN.subVectors(s,i),yN.subVectors(n,i),xN.subVectors(t,i);const o=vN.dot(xN),l=yN.dot(xN);if(o<=0&&l<=0)return e.copy(i);TN.subVectors(t,s);const h=vN.dot(TN),c=yN.dot(TN);if(h>=0&&c<=h)return e.copy(s);const d=o*c-h*l;if(d<=0&&o>=0&&h<=0)return r=o/(o-h),e.copy(i).addScaledVector(vN,r);EN.subVectors(t,n);const u=vN.dot(EN),p=yN.dot(EN);if(p>=0&&u<=p)return e.copy(n);const f=u*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(yN,a);const m=h*p-u*c;if(m<=0&&c-h>=0&&u-p>=0)return SN.subVectors(n,s),a=(c-h)/(c-h+(u-p)),e.copy(s).addScaledVector(SN,a);const _=1/(m+f+d);return r=f*_,a=d*_,e.copy(i).addScaledVector(vN,r).addScaledVector(yN,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let AN=0;class CN extends CI{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:AN++}),this.uuid=LI(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=gD,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=fI,this.stencilZFail=fI,this.stencilZPass=fI,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.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const i=t[e];if(void 0===i)continue;const s=this[e];void 0!==s&&(s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[e]=i)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function s(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(i.blending=this.blending),0!==this.side&&(i.side=this.side),!0===this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=!0),i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.stencilWrite=this.stencilWrite,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaHash&&(i.alphaHash=!0),!0===this.alphaToCoverage&&(i.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=!0),!0===this.forceSinglePass&&(i.forceSinglePass=!0),!0===this.wireframe&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=!0),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),e){const e=s(t.textures),n=s(t.images);e.length>0&&(i.textures=e),n.length>0&&(i.images=n)}return i}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(null!==e){const t=e.length;i=new Array(t);for(let s=0;s!==t;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}const MN={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},PN={h:0,s:0,l:0},RN={h:0,s:0,l:0};function LN(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}class DN{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(void 0===e&&void 0===i){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=aI){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,KI.toWorkingColorSpace(this,e),this}setRGB(t,e,i,s=KI.workingColorSpace){return this.r=t,this.g=e,this.b=i,KI.toWorkingColorSpace(this,s),this}setHSL(t,e,i,s=KI.workingColorSpace){if(t=function(t,e){return(t%e+e)%e}(t,1),e=DI(e,0,1),i=DI(i,0,1),0===e)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,n=2*i-s;this.r=LN(n,s,t+1/3),this.g=LN(n,s,t),this.b=LN(n,s,t-1/3)}return KI.toWorkingColorSpace(this,s),this}setStyle(t,e=aI){function i(t){void 0!==t&&parseFloat(t)}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let t;const n=s[1],r=s[2];switch(n){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setRGB(Math.min(255,parseInt(t[1],10))/255,Math.min(255,parseInt(t[2],10))/255,Math.min(255,parseInt(t[3],10))/255,e);if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setRGB(Math.min(100,parseInt(t[1],10))/100,Math.min(100,parseInt(t[2],10))/100,Math.min(100,parseInt(t[3],10))/100,e);break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setHSL(parseFloat(t[1])/360,parseFloat(t[2])/100,parseFloat(t[3])/100,e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=s[1],i=t.length;if(3===i)return this.setRGB(parseInt(t.charAt(0),16)/15,parseInt(t.charAt(1),16)/15,parseInt(t.charAt(2),16)/15,e);if(6===i)return this.setHex(parseInt(t,16),e)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=aI){const i=MN[t.toLowerCase()];return void 0!==i&&this.setHex(i,e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=ZI(t.r),this.g=ZI(t.g),this.b=ZI(t.b),this}copyLinearToSRGB(t){return this.r=QI(t.r),this.g=QI(t.g),this.b=QI(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=aI){return KI.fromWorkingColorSpace(IN.copy(this),t),65536*Math.round(DI(255*IN.r,0,255))+256*Math.round(DI(255*IN.g,0,255))+Math.round(DI(255*IN.b,0,255))}getHexString(t=aI){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=KI.workingColorSpace){KI.fromWorkingColorSpace(IN.copy(this),e);const i=IN.r,s=IN.g,n=IN.b,r=Math.max(i,s,n),a=Math.min(i,s,n);let o,l;const h=(a+r)/2;if(a===r)o=0,l=0;else{const t=r-a;switch(l=h<=.5?t/(r+a):t/(2-r-a),r){case i:o=(s-n)/t+(s<n?6:0);break;case s:o=(n-i)/t+2;break;case n:o=(i-s)/t+4}o/=6}return t.h=o,t.s=l,t.l=h,t}getRGB(t,e=KI.workingColorSpace){return KI.fromWorkingColorSpace(IN.copy(this),e),t.r=IN.r,t.g=IN.g,t.b=IN.b,t}getStyle(t=aI){KI.fromWorkingColorSpace(IN.copy(this),t);const e=IN.r,i=IN.g,s=IN.b;return t!==aI?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(255*e)},${Math.round(255*i)},${Math.round(255*s)})`}offsetHSL(t,e,i){return this.getHSL(PN),this.setHSL(PN.h+t,PN.s+e,PN.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(PN),t.getHSL(RN);const i=II(PN.h,RN.h,e),s=II(PN.s,RN.s,e),n=II(PN.l,RN.l,e);return this.setHSL(i,s,n),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,s=this.b,n=t.elements;return this.r=n[0]*e+n[3]*i+n[6]*s,this.g=n[1]*e+n[4]*i+n[7]*s,this.b=n[2]*e+n[5]*i+n[8]*s,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const IN=new DN;DN.NAMES=MN;class ON extends CN{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new DN(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.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const NN=new uO,FN=new BI;class UN{constructor(t,e,i=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=35044,this.updateRange={offset:0,count:-1},this.gpuType=qD,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let s=0,n=this.itemSize;s<n;s++)this.array[t+s]=e.array[i+s];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(2===this.itemSize)for(let e=0,i=this.count;e<i;e++)FN.fromBufferAttribute(this,e),FN.applyMatrix3(t),this.setXY(e,FN.x,FN.y);else if(3===this.itemSize)for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyMatrix3(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyMatrix4(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyNormalMatrix(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.transformDirection(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=FI(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=UI(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=FI(e,this.array)),e}setX(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=FI(e,this.array)),e}setY(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=FI(e,this.array)),e}setZ(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=FI(e,this.array)),e}setW(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,s){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array),s=UI(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this}setXYZW(t,e,i,s,n){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array),s=UI(s,this.array),n=UI(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this.array[t+3]=n,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(t.name=this.name),35044!==this.usage&&(t.usage=this.usage),0===this.updateRange.offset&&-1===this.updateRange.count||(t.updateRange=this.updateRange),t}}class BN extends UN{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class zN extends UN{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class kN extends UN{constructor(t,e,i){super(new Float32Array(t),e,i)}}let VN=0;const HN=new HO,GN=new pN,WN=new uO,XN=new mO,YN=new mO,qN=new uO;class jN extends CI{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:VN++}),this.uuid=LI(),this.name="",this.type="BufferGeometry",this.index=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(t){return Array.isArray(t)?this.index=new(VI(t)?zN:BN)(t,1):this.index=t,this}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const e=(new zI).getNormalMatrix(t);i.applyNormalMatrix(e),i.needsUpdate=!0}const s=this.attributes.tangent;return void 0!==s&&(s.transformDirection(t),s.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return HN.makeRotationFromQuaternion(t),this.applyMatrix4(HN),this}rotateX(t){return HN.makeRotationX(t),this.applyMatrix4(HN),this}rotateY(t){return HN.makeRotationY(t),this.applyMatrix4(HN),this}rotateZ(t){return HN.makeRotationZ(t),this.applyMatrix4(HN),this}translate(t,e,i){return HN.makeTranslation(t,e,i),this.applyMatrix4(HN),this}scale(t,e,i){return HN.makeScale(t,e,i),this.applyMatrix4(HN),this}lookAt(t){return GN.lookAt(t),GN.updateMatrix(),this.applyMatrix4(GN.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(WN).negate(),this.translate(WN.x,WN.y,WN.z),this}setFromPoints(t){const e=[];for(let i=0,s=t.length;i<s;i++){const s=t[i];e.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new kN(e,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new mO);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)this.boundingBox.set(new uO(-1/0,-1/0,-1/0),new uO(1/0,1/0,1/0));else{if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t<i;t++){const i=e[t];XN.setFromBufferAttribute(i),this.morphTargetsRelative?(qN.addVectors(this.boundingBox.min,XN.min),this.boundingBox.expandByPoint(qN),qN.addVectors(this.boundingBox.max,XN.max),this.boundingBox.expandByPoint(qN)):(this.boundingBox.expandByPoint(XN.min),this.boundingBox.expandByPoint(XN.max))}}else this.boundingBox.makeEmpty();isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z)}}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new IO);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)this.boundingSphere.set(new uO,1/0);else if(t){const i=this.boundingSphere.center;if(XN.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t<i;t++){const i=e[t];YN.setFromBufferAttribute(i),this.morphTargetsRelative?(qN.addVectors(XN.min,YN.min),XN.expandByPoint(qN),qN.addVectors(XN.max,YN.max),XN.expandByPoint(qN)):(XN.expandByPoint(YN.min),XN.expandByPoint(YN.max))}XN.getCenter(i);let s=0;for(let e=0,n=t.count;e<n;e++)qN.fromBufferAttribute(t,e),s=Math.max(s,i.distanceToSquared(qN));if(e)for(let n=0,r=e.length;n<r;n++){const r=e[n],a=this.morphTargetsRelative;for(let e=0,n=r.count;e<n;e++)qN.fromBufferAttribute(r,e),a&&(WN.fromBufferAttribute(t,e),qN.add(WN)),s=Math.max(s,i.distanceToSquared(qN))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)}}computeTangents(){const t=this.index,e=this.attributes;if(null===t||void 0===e.position||void 0===e.normal||void 0===e.uv)return;const i=t.array,s=e.position.array,n=e.normal.array,r=e.uv.array,a=s.length/3;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new UN(new Float32Array(4*a),4));const o=this.getAttribute("tangent").array,l=[],h=[];for(let t=0;t<a;t++)l[t]=new uO,h[t]=new uO;const c=new uO,d=new uO,u=new uO,p=new BI,f=new BI,m=new BI,_=new uO,g=new uO;function v(t,e,i){c.fromArray(s,3*t),d.fromArray(s,3*e),u.fromArray(s,3*i),p.fromArray(r,2*t),f.fromArray(r,2*e),m.fromArray(r,2*i),d.sub(c),u.sub(c),f.sub(p),m.sub(p);const n=1/(f.x*m.y-m.x*f.y);isFinite(n)&&(_.copy(d).multiplyScalar(m.y).addScaledVector(u,-f.y).multiplyScalar(n),g.copy(u).multiplyScalar(f.x).addScaledVector(d,-m.x).multiplyScalar(n),l[t].add(_),l[e].add(_),l[i].add(_),h[t].add(g),h[e].add(g),h[i].add(g))}let y=this.groups;0===y.length&&(y=[{start:0,count:i.length}]);for(let t=0,e=y.length;t<e;++t){const e=y[t],s=e.start;for(let t=s,n=s+e.count;t<n;t+=3)v(i[t+0],i[t+1],i[t+2])}const S=new uO,x=new uO,T=new uO,E=new uO;function b(t){T.fromArray(n,3*t),E.copy(T);const e=l[t];S.copy(e),S.sub(T.multiplyScalar(T.dot(e))).normalize(),x.crossVectors(E,e);const i=x.dot(h[t])<0?-1:1;o[4*t]=S.x,o[4*t+1]=S.y,o[4*t+2]=S.z,o[4*t+3]=i}for(let t=0,e=y.length;t<e;++t){const e=y[t],s=e.start;for(let t=s,n=s+e.count;t<n;t+=3)b(i[t+0]),b(i[t+1]),b(i[t+2])}}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(void 0!==e){let i=this.getAttribute("normal");if(void 0===i)i=new UN(new Float32Array(3*e.count),3),this.setAttribute("normal",i);else for(let t=0,e=i.count;t<e;t++)i.setXYZ(t,0,0,0);const s=new uO,n=new uO,r=new uO,a=new uO,o=new uO,l=new uO,h=new uO,c=new uO;if(t)for(let d=0,u=t.count;d<u;d+=3){const u=t.getX(d+0),p=t.getX(d+1),f=t.getX(d+2);s.fromBufferAttribute(e,u),n.fromBufferAttribute(e,p),r.fromBufferAttribute(e,f),h.subVectors(r,n),c.subVectors(s,n),h.cross(c),a.fromBufferAttribute(i,u),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,f),a.add(h),o.add(h),l.add(h),i.setXYZ(u,a.x,a.y,a.z),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(f,l.x,l.y,l.z)}else for(let t=0,a=e.count;t<a;t+=3)s.fromBufferAttribute(e,t+0),n.fromBufferAttribute(e,t+1),r.fromBufferAttribute(e,t+2),h.subVectors(r,n),c.subVectors(s,n),h.cross(c),i.setXYZ(t+0,h.x,h.y,h.z),i.setXYZ(t+1,h.x,h.y,h.z),i.setXYZ(t+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)qN.fromBufferAttribute(t,e),qN.normalize(),t.setXYZ(e,qN.x,qN.y,qN.z)}toNonIndexed(){function t(t,e){const i=t.array,s=t.itemSize,n=t.normalized,r=new i.constructor(e.length*s);let a=0,o=0;for(let n=0,l=e.length;n<l;n++){a=t.isInterleavedBufferAttribute?e[n]*t.data.stride+t.offset:e[n]*s;for(let t=0;t<s;t++)r[o++]=i[a++]}return new UN(r,s,n)}if(null===this.index)return this;const e=new jN,i=this.index.array,s=this.attributes;for(const n in s){const r=t(s[n],i);e.setAttribute(n,r)}const n=this.morphAttributes;for(const s in n){const r=[],a=n[s];for(let e=0,s=a.length;e<s;e++){const s=t(a[e],i);r.push(s)}e.morphAttributes[s]=r}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let t=0,i=r.length;t<i;t++){const i=r[t];e.addGroup(i.start,i.count,i.materialIndex)}return e}toJSON(){const t={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,""!==this.name&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const i in e)void 0!==e[i]&&(t[i]=e[i]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const e in i){const s=i[e];t.data.attributes[e]=s.toJSON(t.data)}const s={};let n=!1;for(const e in this.morphAttributes){const i=this.morphAttributes[e],r=[];for(let e=0,s=i.length;e<s;e++){const s=i[e];r.push(s.toJSON(t.data))}r.length>0&&(s[e]=r,n=!0)}n&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;null!==i&&this.setIndex(i.clone(e));const s=t.attributes;for(const t in s){const i=s[t];this.setAttribute(t,i.clone(e))}const n=t.morphAttributes;for(const t in n){const i=[],s=n[t];for(let t=0,n=s.length;t<n;t++)i.push(s[t].clone(e));this.morphAttributes[t]=i}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let t=0,e=r.length;t<e;t++){const e=r[t];this.addGroup(e.start,e.count,e.materialIndex)}const a=t.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=t.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const $N=new HO,KN=new VO,ZN=new IO,QN=new uO,JN=new uO,tF=new uO,eF=new uO,iF=new uO,sF=new uO,nF=new BI,rF=new BI,aF=new BI,oF=new uO,lF=new uO,hF=new uO,cF=new uO,dF=new uO;class uF extends pN{constructor(t=new jN,e=new ON){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;t<e;t++){const e=i[t].name||String(t);this.morphTargetInfluences.push(0),this.morphTargetDictionary[e]=t}}}}getVertexPosition(t,e){const i=this.geometry,s=i.attributes.position,n=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(s,t);const a=this.morphTargetInfluences;if(n&&a){sF.set(0,0,0);for(let i=0,s=n.length;i<s;i++){const s=a[i],o=n[i];0!==s&&(iF.fromBufferAttribute(o,t),r?sF.addScaledVector(iF,s):sF.addScaledVector(iF.sub(e),s))}e.add(sF)}return e}raycast(t,e){const i=this.geometry,s=this.material,n=this.matrixWorld;if(void 0!==s){if(null===i.boundingSphere&&i.computeBoundingSphere(),ZN.copy(i.boundingSphere),ZN.applyMatrix4(n),KN.copy(t.ray).recast(t.near),!1===ZN.containsPoint(KN.origin)){if(null===KN.intersectSphere(ZN,QN))return;if(KN.origin.distanceToSquared(QN)>(t.far-t.near)**2)return}$N.copy(n).invert(),KN.copy(t.ray).applyMatrix4($N),null!==i.boundingBox&&!1===KN.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,KN)}}_computeIntersections(t,e,i){let s;const n=this.geometry,r=this.material,a=n.index,o=n.attributes.position,l=n.attributes.uv,h=n.attributes.uv1,c=n.attributes.normal,d=n.groups,u=n.drawRange;if(null!==a)if(Array.isArray(r))for(let n=0,o=d.length;n<o;n++){const o=d[n],p=r[o.materialIndex];for(let n=Math.max(o.start,u.start),r=Math.min(a.count,Math.min(o.start+o.count,u.start+u.count));n<r;n+=3){s=pF(this,p,t,i,l,h,c,a.getX(n),a.getX(n+1),a.getX(n+2)),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=o.materialIndex,e.push(s))}}else{for(let n=Math.max(0,u.start),o=Math.min(a.count,u.start+u.count);n<o;n+=3){s=pF(this,r,t,i,l,h,c,a.getX(n),a.getX(n+1),a.getX(n+2)),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}else if(void 0!==o)if(Array.isArray(r))for(let n=0,a=d.length;n<a;n++){const a=d[n],p=r[a.materialIndex];for(let n=Math.max(a.start,u.start),r=Math.min(o.count,Math.min(a.start+a.count,u.start+u.count));n<r;n+=3){s=pF(this,p,t,i,l,h,c,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=a.materialIndex,e.push(s))}}else{for(let n=Math.max(0,u.start),a=Math.min(o.count,u.start+u.count);n<a;n+=3){s=pF(this,r,t,i,l,h,c,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}}}function pF(t,e,i,s,n,r,a,o,l,h){t.getVertexPosition(o,JN),t.getVertexPosition(l,tF),t.getVertexPosition(h,eF);const c=function(t,e,i,s,n,r,a,o){let l;if(l=1===e.side?s.intersectTriangle(a,r,n,!0,o):s.intersectTriangle(n,r,a,0===e.side,o),null===l)return null;dF.copy(o),dF.applyMatrix4(t.matrixWorld);const h=i.ray.origin.distanceTo(dF);return h<i.near||h>i.far?null:{distance:h,point:dF.clone(),object:t}}(t,e,i,s,JN,tF,eF,cF);if(c){n&&(nF.fromBufferAttribute(n,o),rF.fromBufferAttribute(n,l),aF.fromBufferAttribute(n,h),c.uv=wN.getInterpolation(cF,JN,tF,eF,nF,rF,aF,new BI)),r&&(nF.fromBufferAttribute(r,o),rF.fromBufferAttribute(r,l),aF.fromBufferAttribute(r,h),c.uv1=wN.getInterpolation(cF,JN,tF,eF,nF,rF,aF,new BI),c.uv2=c.uv1),a&&(oF.fromBufferAttribute(a,o),lF.fromBufferAttribute(a,l),hF.fromBufferAttribute(a,h),c.normal=wN.getInterpolation(cF,JN,tF,eF,oF,lF,hF,new uO),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:h,normal:new uO,materialIndex:0};wN.getNormal(JN,tF,eF,t.normal),c.face=t}return c}class fF extends jN{constructor(t=1,e=1,i=1,s=1,n=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:s,heightSegments:n,depthSegments:r};const a=this;s=Math.floor(s),n=Math.floor(n),r=Math.floor(r);const o=[],l=[],h=[],c=[];let d=0,u=0;function p(t,e,i,s,n,r,p,f,m,_,g){const v=r/m,y=p/_,S=r/2,x=p/2,T=f/2,E=m+1,b=_+1;let w=0,A=0;const C=new uO;for(let r=0;r<b;r++){const a=r*y-x;for(let o=0;o<E;o++){const d=o*v-S;C[t]=d*s,C[e]=a*n,C[i]=T,l.push(C.x,C.y,C.z),C[t]=0,C[e]=0,C[i]=f>0?1:-1,h.push(C.x,C.y,C.z),c.push(o/m),c.push(1-r/_),w+=1}}for(let t=0;t<_;t++)for(let e=0;e<m;e++){const i=d+e+E*t,s=d+e+E*(t+1),n=d+(e+1)+E*(t+1),r=d+(e+1)+E*t;o.push(i,s,r),o.push(s,n,r),A+=6}a.addGroup(u,A,g),u+=A,d+=w}p("z","y","x",-1,-1,i,e,t,r,n,0),p("z","y","x",1,-1,i,e,-t,r,n,1),p("x","z","y",1,1,t,i,e,s,r,2),p("x","z","y",1,-1,t,i,-e,s,r,3),p("x","y","z",1,-1,t,e,i,s,n,4),p("x","y","z",-1,-1,t,e,-i,s,n,5),this.setIndex(o),this.setAttribute("position",new kN(l,3)),this.setAttribute("normal",new kN(h,3)),this.setAttribute("uv",new kN(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new fF(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}function mF(t){const e={};for(const i in t){e[i]={};for(const s in t[i]){const n=t[i][s];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?e[i][s]=null:e[i][s]=n.clone():Array.isArray(n)?e[i][s]=n.slice():e[i][s]=n}}return e}function _F(t){const e={};for(let i=0;i<t.length;i++){const s=mF(t[i]);for(const t in s)e[t]=s[t]}return e}function gF(t){return null===t.getRenderTarget()?t.outputColorSpace:KI.workingColorSpace}const vF={clone:mF,merge:_F};class yF extends CN{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==t&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=mF(t.uniforms),this.uniformsGroups=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].clone());return e}(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const i in this.uniforms){const s=this.uniforms[i].value;s&&s.isTexture?e.uniforms[i]={type:"t",value:s.toJSON(t).uuid}:s&&s.isColor?e.uniforms[i]={type:"c",value:s.getHex()}:s&&s.isVector2?e.uniforms[i]={type:"v2",value:s.toArray()}:s&&s.isVector3?e.uniforms[i]={type:"v3",value:s.toArray()}:s&&s.isVector4?e.uniforms[i]={type:"v4",value:s.toArray()}:s&&s.isMatrix3?e.uniforms[i]={type:"m3",value:s.toArray()}:s&&s.isMatrix4?e.uniforms[i]={type:"m4",value:s.toArray()}:e.uniforms[i]={value:s}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const t in this.extensions)!0===this.extensions[t]&&(i[t]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}}let SF=class extends pN{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new HO,this.projectionMatrix=new HO,this.projectionMatrixInverse=new HO,this.coordinateSystem=wI}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}};class xF extends SF{constructor(t=50,e=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*RI*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*PI*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*RI*Math.atan(Math.tan(.5*PI*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,i,s,n,r){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*PI*this.fov)/this.zoom,i=2*e,s=this.aspect*i,n=-.5*s;const r=this.view;if(null!==this.view&&this.view.enabled){const t=r.fullWidth,a=r.fullHeight;n+=r.offsetX*s/t,e-=r.offsetY*i/a,s*=r.width/t,i*=r.height/a}const a=this.filmOffset;0!==a&&(n+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+s,e,e-i,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const TF=-90;class EF extends pN{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new xF(TF,1,t,e);s.layers=this.layers,this.add(s);const n=new xF(TF,1,t,e);n.layers=this.layers,this.add(n);const r=new xF(TF,1,t,e);r.layers=this.layers,this.add(r);const a=new xF(TF,1,t,e);a.layers=this.layers,this.add(a);const o=new xF(TF,1,t,e);o.layers=this.layers,this.add(o);const l=new xF(TF,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,s,n,r,a,o]=e;for(const t of e)this.remove(t);if(t===wI)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.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),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==AI)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.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),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[n,r,a,o,l,h]=this.children,c=t.getRenderTarget(),d=t.getActiveCubeFace(),u=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const f=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,t.setRenderTarget(i,0,s),t.render(e,n),t.setRenderTarget(i,1,s),t.render(e,r),t.setRenderTarget(i,2,s),t.render(e,a),t.setRenderTarget(i,3,s),t.render(e,o),t.setRenderTarget(i,4,s),t.render(e,l),i.texture.generateMipmaps=f,t.setRenderTarget(i,5,s),t.render(e,h),t.setRenderTarget(c,d,u),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class bF extends rO{constructor(t,e,i,s,n,r,a,o,l,h){super(t=void 0!==t?t:[],e=void 0!==e?e:LD,i,s,n,r,a,o,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class wF extends lO{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const i={width:t,height:t,depth:1},s=[i,i,i,i,i,i];void 0!==e.encoding&&(XI("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),e.colorSpace=e.encoding===nI?aI:rI),this.texture=new bF(s,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:kD}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},s=new fF(5,5,5),n=new yF({name:"CubemapFromEquirect",uniforms:mF(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});n.uniforms.tEquirect.value=e;const r=new uF(s,n),a=e.minFilter;e.minFilter===HD&&(e.minFilter=kD);return new EF(1,10,this).update(t,r),e.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(t,e,i,s){const n=t.getRenderTarget();for(let n=0;n<6;n++)t.setRenderTarget(this,n),t.clear(e,i,s);t.setRenderTarget(n)}}const AF=new uO,CF=new uO,MF=new zI;class PF{constructor(t=new uO(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,s){return this.normal.set(t,e,i),this.constant=s,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const s=AF.subVectors(i,e).cross(CF.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(s,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const i=t.delta(AF),s=this.normal.dot(i);if(0===s)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const n=-(t.start.dot(this.normal)+this.constant)/s;return n<0||n>1?null:e.copy(t.start).addScaledVector(i,n)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||MF.getNormalMatrix(t),s=this.coplanarPoint(AF).applyMatrix4(t),n=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(n),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const RF=new IO,LF=new uO;class DF{constructor(t=new PF,e=new PF,i=new PF,s=new PF,n=new PF,r=new PF){this.planes=[t,e,i,s,n,r]}set(t,e,i,s,n,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(s),a[4].copy(n),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=2e3){const i=this.planes,s=t.elements,n=s[0],r=s[1],a=s[2],o=s[3],l=s[4],h=s[5],c=s[6],d=s[7],u=s[8],p=s[9],f=s[10],m=s[11],_=s[12],g=s[13],v=s[14],y=s[15];if(i[0].setComponents(o-n,d-l,m-u,y-_).normalize(),i[1].setComponents(o+n,d+l,m+u,y+_).normalize(),i[2].setComponents(o+r,d+h,m+p,y+g).normalize(),i[3].setComponents(o-r,d-h,m-p,y-g).normalize(),i[4].setComponents(o-a,d-c,m-f,y-v).normalize(),e===wI)i[5].setComponents(o+a,d+c,m+f,y+v).normalize();else{if(e!==AI)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);i[5].setComponents(a,c,f,v).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),RF.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),RF.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(RF)}intersectsSprite(t){return RF.center.set(0,0,0),RF.radius=.7071067811865476,RF.applyMatrix4(t.matrixWorld),this.intersectsSphere(RF)}intersectsSphere(t){const e=this.planes,i=t.center,s=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(i)<s)return!1}return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const s=e[i];if(LF.x=s.normal.x>0?t.max.x:t.min.x,LF.y=s.normal.y>0?t.max.y:t.min.y,LF.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(LF)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function IF(){let t=null,e=!1,i=null,s=null;function n(e,r){i(e,r),s=t.requestAnimationFrame(n)}return{start:function(){!0!==e&&null!==i&&(s=t.requestAnimationFrame(n),e=!0)},stop:function(){t.cancelAnimationFrame(s),e=!1},setAnimationLoop:function(t){i=t},setContext:function(e){t=e}}}function OF(t,e){const i=e.isWebGL2,s=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),s.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const i=s.get(e);i&&(t.deleteBuffer(i.buffer),s.delete(e))},update:function(e,n){if(e.isGLBufferAttribute){const t=s.get(e);return void((!t||t.version<e.version)&&s.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version}))}e.isInterleavedBufferAttribute&&(e=e.data);const r=s.get(e);void 0===r?s.set(e,function(e,s){const n=e.array,r=e.usage,a=t.createBuffer();let o;if(t.bindBuffer(s,a),t.bufferData(s,n,r),e.onUploadCallback(),n instanceof Float32Array)o=t.FLOAT;else if(n instanceof Uint16Array)if(e.isFloat16BufferAttribute){if(!i)throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");o=t.HALF_FLOAT}else o=t.UNSIGNED_SHORT;else if(n instanceof Int16Array)o=t.SHORT;else if(n instanceof Uint32Array)o=t.UNSIGNED_INT;else if(n instanceof Int32Array)o=t.INT;else if(n instanceof Int8Array)o=t.BYTE;else if(n instanceof Uint8Array)o=t.UNSIGNED_BYTE;else{if(!(n instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+n);o=t.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version}}(e,n)):r.version<e.version&&(!function(e,s,n){const r=s.array,a=s.updateRange;t.bindBuffer(n,e),-1===a.count?t.bufferSubData(n,0,r):(i?t.bufferSubData(n,a.offset*r.BYTES_PER_ELEMENT,r,a.offset,a.count):t.bufferSubData(n,a.offset*r.BYTES_PER_ELEMENT,r.subarray(a.offset,a.offset+a.count)),a.count=-1),s.onUploadCallback()}(r.buffer,e,n),r.version=e.version)}}}class NF extends jN{constructor(t=1,e=1,i=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:s};const n=t/2,r=e/2,a=Math.floor(i),o=Math.floor(s),l=a+1,h=o+1,c=t/a,d=e/o,u=[],p=[],f=[],m=[];for(let t=0;t<h;t++){const e=t*d-r;for(let i=0;i<l;i++){const s=i*c-n;p.push(s,-e,0),f.push(0,0,1),m.push(i/a),m.push(1-t/o)}}for(let t=0;t<o;t++)for(let e=0;e<a;e++){const i=e+l*t,s=e+l*(t+1),n=e+1+l*(t+1),r=e+1+l*t;u.push(i,s,r),u.push(s,n,r)}this.setIndex(u),this.setAttribute("position",new kN(p,3)),this.setAttribute("normal",new kN(f,3)),this.setAttribute("uv",new kN(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new NF(t.width,t.height,t.widthSegments,t.heightSegments)}}const FF={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tanisotropyV /= material.anisotropy;\n\tmaterial.anisotropy = saturate( material.anisotropy );\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x - tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x + tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal;\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},UF={common:{diffuse:{value:new DN(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new zI},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new zI}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new zI}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new zI}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new zI},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new zI},normalScale:{value:new BI(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new zI},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new zI}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new zI}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new zI}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new DN(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new DN(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0},uvTransform:{value:new zI}},sprite:{diffuse:{value:new DN(16777215)},opacity:{value:1},center:{value:new BI(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new zI},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0}}},BF={basic:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.fog]),vertexShader:FF.meshbasic_vert,fragmentShader:FF.meshbasic_frag},lambert:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,UF.lights,{emissive:{value:new DN(0)}}]),vertexShader:FF.meshlambert_vert,fragmentShader:FF.meshlambert_frag},phong:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,UF.lights,{emissive:{value:new DN(0)},specular:{value:new DN(1118481)},shininess:{value:30}}]),vertexShader:FF.meshphong_vert,fragmentShader:FF.meshphong_frag},standard:{uniforms:_F([UF.common,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.roughnessmap,UF.metalnessmap,UF.fog,UF.lights,{emissive:{value:new DN(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:FF.meshphysical_vert,fragmentShader:FF.meshphysical_frag},toon:{uniforms:_F([UF.common,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.gradientmap,UF.fog,UF.lights,{emissive:{value:new DN(0)}}]),vertexShader:FF.meshtoon_vert,fragmentShader:FF.meshtoon_frag},matcap:{uniforms:_F([UF.common,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,{matcap:{value:null}}]),vertexShader:FF.meshmatcap_vert,fragmentShader:FF.meshmatcap_frag},points:{uniforms:_F([UF.points,UF.fog]),vertexShader:FF.points_vert,fragmentShader:FF.points_frag},dashed:{uniforms:_F([UF.common,UF.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:FF.linedashed_vert,fragmentShader:FF.linedashed_frag},depth:{uniforms:_F([UF.common,UF.displacementmap]),vertexShader:FF.depth_vert,fragmentShader:FF.depth_frag},normal:{uniforms:_F([UF.common,UF.bumpmap,UF.normalmap,UF.displacementmap,{opacity:{value:1}}]),vertexShader:FF.meshnormal_vert,fragmentShader:FF.meshnormal_frag},sprite:{uniforms:_F([UF.sprite,UF.fog]),vertexShader:FF.sprite_vert,fragmentShader:FF.sprite_frag},background:{uniforms:{uvTransform:{value:new zI},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:FF.background_vert,fragmentShader:FF.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:FF.backgroundCube_vert,fragmentShader:FF.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:FF.cube_vert,fragmentShader:FF.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:FF.equirect_vert,fragmentShader:FF.equirect_frag},distanceRGBA:{uniforms:_F([UF.common,UF.displacementmap,{referencePosition:{value:new uO},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:FF.distanceRGBA_vert,fragmentShader:FF.distanceRGBA_frag},shadow:{uniforms:_F([UF.lights,UF.fog,{color:{value:new DN(0)},opacity:{value:1}}]),vertexShader:FF.shadow_vert,fragmentShader:FF.shadow_frag}};BF.physical={uniforms:_F([BF.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new zI},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new zI},clearcoatNormalScale:{value:new BI(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new zI},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new zI},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new zI},sheen:{value:0},sheenColor:{value:new DN(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new zI},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new zI},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new zI},transmissionSamplerSize:{value:new BI},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new zI},attenuationDistance:{value:0},attenuationColor:{value:new DN(0)},specularColor:{value:new DN(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new zI},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new zI},anisotropyVector:{value:new BI},anisotropyMap:{value:null},anisotropyMapTransform:{value:new zI}}]),vertexShader:FF.meshphysical_vert,fragmentShader:FF.meshphysical_frag};const zF={r:0,b:0,g:0};function kF(t,e,i,s,n,r,a){const o=new DN(0);let l,h,c=!0===r?0:1,d=null,u=0,p=null;function f(e,i){e.getRGB(zF,gF(t)),s.buffers.color.setClear(zF.r,zF.g,zF.b,i,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),c=e,f(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(t){c=t,f(o,c)},render:function(r,m){let _=!1,g=!0===m.isScene?m.background:null;if(g&&g.isTexture){g=(m.backgroundBlurriness>0?i:e).get(g)}null===g?f(o,c):g&&g.isColor&&(f(g,1),_=!0);const v=t.xr.getEnvironmentBlendMode();"additive"===v?s.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===v&&s.buffers.color.setClear(0,0,0,0,a),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),g&&(g.isCubeTexture||g.mapping===ID)?(void 0===h&&(h=new uF(new fF(1,1,1),new yF({name:"BackgroundCubeMaterial",uniforms:mF(BF.backgroundCube.uniforms),vertexShader:BF.backgroundCube.vertexShader,fragmentShader:BF.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(t,e,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h.material.uniforms.envMap.value=g,h.material.uniforms.flipEnvMap.value=g.isCubeTexture&&!1===g.isRenderTargetTexture?-1:1,h.material.uniforms.backgroundBlurriness.value=m.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=m.backgroundIntensity,h.material.toneMapped=KI.getTransfer(g.colorSpace)!==dI,d===g&&u===g.version&&p===t.toneMapping||(h.material.needsUpdate=!0,d=g,u=g.version,p=t.toneMapping),h.layers.enableAll(),r.unshift(h,h.geometry,h.material,0,0,null)):g&&g.isTexture&&(void 0===l&&(l=new uF(new NF(2,2),new yF({name:"BackgroundMaterial",uniforms:mF(BF.background.uniforms),vertexShader:BF.background.vertexShader,fragmentShader:BF.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=g,l.material.uniforms.backgroundIntensity.value=m.backgroundIntensity,l.material.toneMapped=KI.getTransfer(g.colorSpace)!==dI,!0===g.matrixAutoUpdate&&g.updateMatrix(),l.material.uniforms.uvTransform.value.copy(g.matrix),d===g&&u===g.version&&p===t.toneMapping||(l.material.needsUpdate=!0,d=g,u=g.version,p=t.toneMapping),l.layers.enableAll(),r.unshift(l,l.geometry,l.material,0,0,null))}}}function VF(t,e,i,s){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r=s.isWebGL2?null:e.get("OES_vertex_array_object"),a=s.isWebGL2||null!==r,o={},l=p(null);let h=l,c=!1;function d(e){return s.isWebGL2?t.bindVertexArray(e):r.bindVertexArrayOES(e)}function u(e){return s.isWebGL2?t.deleteVertexArray(e):r.deleteVertexArrayOES(e)}function p(t){const e=[],i=[],s=[];for(let t=0;t<n;t++)e[t]=0,i[t]=0,s[t]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:e,enabledAttributes:i,attributeDivisors:s,object:t,attributes:{},index:null}}function f(){const t=h.newAttributes;for(let e=0,i=t.length;e<i;e++)t[e]=0}function m(t){_(t,0)}function _(i,n){const r=h.newAttributes,a=h.enabledAttributes,o=h.attributeDivisors;if(r[i]=1,0===a[i]&&(t.enableVertexAttribArray(i),a[i]=1),o[i]!==n){(s.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[s.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](i,n),o[i]=n}}function g(){const e=h.newAttributes,i=h.enabledAttributes;for(let s=0,n=i.length;s<n;s++)i[s]!==e[s]&&(t.disableVertexAttribArray(s),i[s]=0)}function v(e,i,s,n,r,a,o){!0===o?t.vertexAttribIPointer(e,i,s,r,a):t.vertexAttribPointer(e,i,s,n,r,a)}function y(){S(),c=!0,h!==l&&(h=l,d(h.object))}function S(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:function(n,l,u,y,S){let x=!1;if(a){const e=function(e,i,n){const a=!0===n.wireframe;let l=o[e.id];void 0===l&&(l={},o[e.id]=l);let h=l[i.id];void 0===h&&(h={},l[i.id]=h);let c=h[a];void 0===c&&(c=p(s.isWebGL2?t.createVertexArray():r.createVertexArrayOES()),h[a]=c);return c}(y,u,l);h!==e&&(h=e,d(h.object)),x=function(t,e,i,s){const n=h.attributes,r=e.attributes;let a=0;const o=i.getAttributes();for(const e in o){if(o[e].location>=0){const i=n[e];let s=r[e];if(void 0===s&&("instanceMatrix"===e&&t.instanceMatrix&&(s=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(s=t.instanceColor)),void 0===i)return!0;if(i.attribute!==s)return!0;if(s&&i.data!==s.data)return!0;a++}}return h.attributesNum!==a||h.index!==s}(n,y,u,S),x&&function(t,e,i,s){const n={},r=e.attributes;let a=0;const o=i.getAttributes();for(const e in o){if(o[e].location>=0){let i=r[e];void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor));const s={};s.attribute=i,i&&i.data&&(s.data=i.data),n[e]=s,a++}}h.attributes=n,h.attributesNum=a,h.index=s}(n,y,u,S)}else{const t=!0===l.wireframe;h.geometry===y.id&&h.program===u.id&&h.wireframe===t||(h.geometry=y.id,h.program=u.id,h.wireframe=t,x=!0)}null!==S&&i.update(S,t.ELEMENT_ARRAY_BUFFER),(x||c)&&(c=!1,function(n,r,a,o){if(!1===s.isWebGL2&&(n.isInstancedMesh||o.isInstancedBufferGeometry)&&null===e.get("ANGLE_instanced_arrays"))return;f();const l=o.attributes,h=a.getAttributes(),c=r.defaultAttributeValues;for(const e in h){const r=h[e];if(r.location>=0){let a=l[e];if(void 0===a&&("instanceMatrix"===e&&n.instanceMatrix&&(a=n.instanceMatrix),"instanceColor"===e&&n.instanceColor&&(a=n.instanceColor)),void 0!==a){const e=a.normalized,l=a.itemSize,h=i.get(a);if(void 0===h)continue;const c=h.buffer,d=h.type,u=h.bytesPerElement,p=!0===s.isWebGL2&&(d===t.INT||d===t.UNSIGNED_INT||a.gpuType===XD);if(a.isInterleavedBufferAttribute){const i=a.data,s=i.stride,h=a.offset;if(i.isInstancedInterleavedBuffer){for(let t=0;t<r.locationSize;t++)_(r.location+t,i.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=i.meshPerAttribute*i.count)}else for(let t=0;t<r.locationSize;t++)m(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)v(r.location+t,l/r.locationSize,d,e,s*u,(h+l/r.locationSize*t)*u,p)}else{if(a.isInstancedBufferAttribute){for(let t=0;t<r.locationSize;t++)_(r.location+t,a.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=a.meshPerAttribute*a.count)}else for(let t=0;t<r.locationSize;t++)m(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)v(r.location+t,l/r.locationSize,d,e,l*u,l/r.locationSize*t*u,p)}}else if(void 0!==c){const i=c[e];if(void 0!==i)switch(i.length){case 2:t.vertexAttrib2fv(r.location,i);break;case 3:t.vertexAttrib3fv(r.location,i);break;case 4:t.vertexAttrib4fv(r.location,i);break;default:t.vertexAttrib1fv(r.location,i)}}}}g()}(n,l,u,y),null!==S&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i.get(S).buffer))},reset:y,resetDefaultState:S,dispose:function(){y();for(const t in o){const e=o[t];for(const t in e){const i=e[t];for(const t in i)u(i[t].object),delete i[t];delete e[t]}delete o[t]}},releaseStatesOfGeometry:function(t){if(void 0===o[t.id])return;const e=o[t.id];for(const t in e){const i=e[t];for(const t in i)u(i[t].object),delete i[t];delete e[t]}delete o[t.id]},releaseStatesOfProgram:function(t){for(const e in o){const i=o[e];if(void 0===i[t.id])continue;const s=i[t.id];for(const t in s)u(s[t].object),delete s[t];delete i[t.id]}},initAttributes:f,enableAttribute:m,disableUnusedAttributes:g}}function HF(t,e,i,s){const n=s.isWebGL2;let r;this.setMode=function(t){r=t},this.render=function(e,s){t.drawArrays(r,e,s),i.update(s,r,1)},this.renderInstances=function(s,a,o){if(0===o)return;let l,h;if(n)l=t,h="drawArraysInstanced";else if(l=e.get("ANGLE_instanced_arrays"),h="drawArraysInstancedANGLE",null===l)return;l[h](r,s,a,o),i.update(a,r,o)}}function GF(t,e,i){let s;function n(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const r="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===t.constructor.name;let a=void 0!==i.precision?i.precision:"highp";const o=n(a);o!==a&&(a=o);const l=r||e.has("WEBGL_draw_buffers"),h=!0===i.logarithmicDepthBuffer,c=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),d=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_TEXTURE_SIZE),p=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),f=t.getParameter(t.MAX_VERTEX_ATTRIBS),m=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),_=t.getParameter(t.MAX_VARYING_VECTORS),g=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),v=d>0,y=r||e.has("OES_texture_float");return{isWebGL2:r,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==s)return s;if(!0===e.has("EXT_texture_filter_anisotropic")){const i=e.get("EXT_texture_filter_anisotropic");s=t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s},getMaxPrecision:n,precision:a,logarithmicDepthBuffer:h,maxTextures:c,maxVertexTextures:d,maxTextureSize:u,maxCubemapSize:p,maxAttributes:f,maxVertexUniforms:m,maxVaryings:_,maxFragmentUniforms:g,vertexTextures:v,floatFragmentTextures:y,floatVertexTextures:v&&y,maxSamples:r?t.getParameter(t.MAX_SAMPLES):0}}function WF(t){const e=this;let i=null,s=0,n=!1,r=!1;const a=new PF,o=new zI,l={value:null,needsUpdate:!1};function h(t,i,s,n){const r=null!==t?t.length:0;let h=null;if(0!==r){if(h=l.value,!0!==n||null===h){const e=s+4*r,n=i.matrixWorldInverse;o.getNormalMatrix(n),(null===h||h.length<e)&&(h=new Float32Array(e));for(let e=0,i=s;e!==r;++e,i+=4)a.copy(t[e]).applyMatrix4(n,o),a.normal.toArray(h,i),h[i+3]=a.constant}l.value=h,l.needsUpdate=!0}return e.numPlanes=r,e.numIntersection=0,h}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(t,e){const i=0!==t.length||e||0!==s||n;return n=e,s=t.length,i},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(t,e){i=h(t,e,0)},this.setState=function(a,o,c){const d=a.clippingPlanes,u=a.clipIntersection,p=a.clipShadows,f=t.get(a);if(!n||null===d||0===d.length||r&&!p)r?h(null):function(){l.value!==i&&(l.value=i,l.needsUpdate=s>0);e.numPlanes=s,e.numIntersection=0}();else{const t=r?0:s,e=4*t;let n=f.clippingState||null;l.value=n,n=h(d,o,e,c);for(let t=0;t!==e;++t)n[t]=i[t];f.clippingState=n,this.numIntersection=u?this.numPlanes:0,this.numPlanes+=t}}}function XF(t){let e=new WeakMap;function i(t,e){return 303===e?t.mapping=LD:304===e&&(t.mapping=DD),t}function s(t){const i=t.target;i.removeEventListener("dispose",s);const n=e.get(i);void 0!==n&&(e.delete(i),n.dispose())}return{get:function(n){if(n&&n.isTexture&&!1===n.isRenderTargetTexture){const r=n.mapping;if(303===r||304===r){if(e.has(n)){return i(e.get(n).texture,n.mapping)}{const r=n.image;if(r&&r.height>0){const a=new wF(r.height/2);return a.fromEquirectangularTexture(t,n),e.set(n,a),n.addEventListener("dispose",s),i(a.texture,n.mapping)}return null}}}return n},dispose:function(){e=new WeakMap}}}class YF extends SF{constructor(t=-1,e=1,i=1,s=-1,n=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=i,this.bottom=s,this.near=n,this.far=r,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,i,s,n,r){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let n=i-t,r=i+t,a=s+e,o=s-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=t*this.view.offsetX,r=n+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(n,r,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const qF=[.125,.215,.35,.446,.526,.582],jF=20,$F=new YF,KF=new DN;let ZF=null;const QF=(1+Math.sqrt(5))/2,JF=1/QF,tU=[new uO(1,1,1),new uO(-1,1,1),new uO(1,1,-1),new uO(-1,1,-1),new uO(0,QF,JF),new uO(0,QF,-JF),new uO(JF,0,QF),new uO(-JF,0,QF),new uO(QF,JF,0),new uO(-QF,JF,0)];class eU{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,i=.1,s=100){ZF=this._renderer.getRenderTarget(),this._setSize(256);const n=this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(t,i,s,n),e>0&&this._blur(n,0,0,e),this._applyPMREM(n),this._cleanup(n),n}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=rU(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nU(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodPlanes.length;t++)this._lodPlanes[t].dispose()}_cleanup(t){this._renderer.setRenderTarget(ZF),t.scissorTest=!1,sU(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===LD||t.mapping===DD?this._setSize(0===t.image.length?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),ZF=this._renderer.getRenderTarget();const i=e||this._allocateTargets();return this._textureToCubeUV(t,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,i={magFilter:kD,minFilter:kD,generateMipmaps:!1,type:jD,format:KD,colorSpace:oI,depthBuffer:!1},s=iU(t,e,i);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=iU(t,e,i);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(t){const e=[],i=[],s=[];let n=t;const r=t-4+1+qF.length;for(let a=0;a<r;a++){const r=Math.pow(2,n);i.push(r);let o=1/r;a>t-4?o=qF[a-t+4-1]:0===a&&(o=0),s.push(o);const l=1/(r-2),h=-l,c=1+l,d=[h,h,c,h,c,c,h,h,c,c,h,c],u=6,p=6,f=3,m=2,_=1,g=new Float32Array(f*p*u),v=new Float32Array(m*p*u),y=new Float32Array(_*p*u);for(let t=0;t<u;t++){const e=t%3*2/3-1,i=t>2?0:-1,s=[e,i,0,e+2/3,i,0,e+2/3,i+1,0,e,i,0,e+2/3,i+1,0,e,i+1,0];g.set(s,f*p*t),v.set(d,m*p*t);const n=[t,t,t,t,t,t];y.set(n,_*p*t)}const S=new jN;S.setAttribute("position",new UN(g,f)),S.setAttribute("uv",new UN(v,m)),S.setAttribute("faceIndex",new UN(y,_)),e.push(S),n>4&&n--}return{lodPlanes:e,sizeLods:i,sigmas:s}}(s)),this._blurMaterial=function(t,e,i){const s=new Float32Array(jF),n=new uO(0,1,0),r=new yF({name:"SphericalGaussianBlur",defines:{n:jF,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:s},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return r}(s,t,e)}return s}_compileMaterial(t){const e=new uF(this._lodPlanes[0],t);this._renderer.compile(e,$F)}_sceneToCubeUV(t,e,i,s){const n=new xF(90,1,e,i),r=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,h=o.toneMapping;o.getClearColor(KF),o.toneMapping=0,o.autoClear=!1;const c=new ON({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new uF(new fF,c);let u=!1;const p=t.background;p?p.isColor&&(c.color.copy(p),t.background=null,u=!0):(c.color.copy(KF),u=!0);for(let e=0;e<6;e++){const i=e%3;0===i?(n.up.set(0,r[e],0),n.lookAt(a[e],0,0)):1===i?(n.up.set(0,0,r[e]),n.lookAt(0,a[e],0)):(n.up.set(0,r[e],0),n.lookAt(0,0,a[e]));const l=this._cubeSize;sU(s,i*l,e>2?l:0,l,l),o.setRenderTarget(s),u&&o.render(d,n),o.render(t,n)}d.geometry.dispose(),d.material.dispose(),o.toneMapping=h,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const i=this._renderer,s=t.mapping===LD||t.mapping===DD;s?(null===this._cubemapMaterial&&(this._cubemapMaterial=rU()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=nU());const n=s?this._cubemapMaterial:this._equirectMaterial,r=new uF(this._lodPlanes[0],n);n.uniforms.envMap.value=t;const a=this._cubeSize;sU(e,0,0,3*a,2*a),i.setRenderTarget(e),i.render(r,$F)}_applyPMREM(t){const e=this._renderer,i=e.autoClear;e.autoClear=!1;for(let e=1;e<this._lodPlanes.length;e++){const i=Math.sqrt(this._sigmas[e]*this._sigmas[e]-this._sigmas[e-1]*this._sigmas[e-1]),s=tU[(e-1)%tU.length];this._blur(t,e-1,e,i,s)}e.autoClear=i}_blur(t,e,i,s,n){const r=this._pingPongRenderTarget;this._halfBlur(t,r,e,i,s,"latitudinal",n),this._halfBlur(r,t,i,i,s,"longitudinal",n)}_halfBlur(t,e,i,s,n,r,a){const o=this._renderer,l=this._blurMaterial,h=new uF(this._lodPlanes[s],l),c=l.uniforms,d=this._sizeLods[i]-1,u=isFinite(n)?Math.PI/(2*d):2*Math.PI/39,p=n/u,f=isFinite(n)?1+Math.floor(3*p):jF,m=[];let _=0;for(let t=0;t<jF;++t){const e=t/p,i=Math.exp(-e*e/2);m.push(i),0===t?_+=i:t<f&&(_+=2*i)}for(let t=0;t<m.length;t++)m[t]=m[t]/_;c.envMap.value=t.texture,c.samples.value=f,c.weights.value=m,c.latitudinal.value="latitudinal"===r,a&&(c.poleAxis.value=a);const{_lodMax:g}=this;c.dTheta.value=u,c.mipInt.value=g-i;const v=this._sizeLods[s];sU(e,3*v*(s>g-4?s-g+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(e),o.render(h,$F)}}function iU(t,e,i){const s=new lO(t,e,i);return s.texture.mapping=ID,s.texture.name="PMREM.cubeUv",s.scissorTest=!0,s}function sU(t,e,i,s,n){t.viewport.set(e,i,s,n),t.scissor.set(e,i,s,n)}function nU(){return new yF({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function rU(){return new yF({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function aU(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function oU(t){let e=new WeakMap,i=null;function s(t){const i=t.target;i.removeEventListener("dispose",s);const n=e.get(i);void 0!==n&&(e.delete(i),n.dispose())}return{get:function(n){if(n&&n.isTexture){const r=n.mapping,a=303===r||304===r,o=r===LD||r===DD;if(a||o){if(n.isRenderTargetTexture&&!0===n.needsPMREMUpdate){n.needsPMREMUpdate=!1;let s=e.get(n);return null===i&&(i=new eU(t)),s=a?i.fromEquirectangular(n,s):i.fromCubemap(n,s),e.set(n,s),s.texture}if(e.has(n))return e.get(n).texture;{const r=n.image;if(a&&r&&r.height>0||o&&r&&function(t){let e=0;const i=6;for(let s=0;s<i;s++)void 0!==t[s]&&e++;return e===i}(r)){null===i&&(i=new eU(t));const r=a?i.fromEquirectangular(n):i.fromCubemap(n);return e.set(n,r),n.addEventListener("dispose",s),r.texture}return null}}}return n},dispose:function(){e=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function lU(t){const e={};function i(i){if(void 0!==e[i])return e[i];let s;switch(i){case"WEBGL_depth_texture":s=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=t.getExtension(i)}return e[i]=s,s}return{has:function(t){return null!==i(t)},init:function(t){t.isWebGL2?i("EXT_color_buffer_float"):(i("WEBGL_depth_texture"),i("OES_texture_float"),i("OES_texture_half_float"),i("OES_texture_half_float_linear"),i("OES_standard_derivatives"),i("OES_element_index_uint"),i("OES_vertex_array_object"),i("ANGLE_instanced_arrays")),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture")},get:function(t){const e=i(t);return e}}}function hU(t,e,i,s){const n={},r=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);for(const t in o.morphAttributes){const i=o.morphAttributes[t];for(let t=0,s=i.length;t<s;t++)e.remove(i[t])}o.removeEventListener("dispose",a),delete n[o.id];const l=r.get(o);l&&(e.remove(l),r.delete(o)),s.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,i.memory.geometries--}function o(t){const i=[],s=t.index,n=t.attributes.position;let a=0;if(null!==s){const t=s.array;a=s.version;for(let e=0,s=t.length;e<s;e+=3){const s=t[e+0],n=t[e+1],r=t[e+2];i.push(s,n,n,r,r,s)}}else{if(void 0===n)return;{const t=n.array;a=n.version;for(let e=0,s=t.length/3-1;e<s;e+=3){const t=e+0,s=e+1,n=e+2;i.push(t,s,s,n,n,t)}}}const o=new(VI(i)?zN:BN)(i,1);o.version=a;const l=r.get(t);l&&e.remove(l),r.set(t,o)}return{get:function(t,e){return!0===n[e.id]||(e.addEventListener("dispose",a),n[e.id]=!0,i.memory.geometries++),e},update:function(i){const s=i.attributes;for(const i in s)e.update(s[i],t.ARRAY_BUFFER);const n=i.morphAttributes;for(const i in n){const s=n[i];for(let i=0,n=s.length;i<n;i++)e.update(s[i],t.ARRAY_BUFFER)}},getWireframeAttribute:function(t){const e=r.get(t);if(e){const i=t.index;null!==i&&e.version<i.version&&o(t)}else o(t);return r.get(t)}}}function cU(t,e,i,s){const n=s.isWebGL2;let r,a,o;this.setMode=function(t){r=t},this.setIndex=function(t){a=t.type,o=t.bytesPerElement},this.render=function(e,s){t.drawElements(r,s,a,e*o),i.update(s,r,1)},this.renderInstances=function(s,l,h){if(0===h)return;let c,d;if(n)c=t,d="drawElementsInstanced";else if(c=e.get("ANGLE_instanced_arrays"),d="drawElementsInstancedANGLE",null===c)return;c[d](r,l,a,s*o,h),i.update(l,r,h)}}function dU(t){const e={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:e,programs:null,autoReset:!0,reset:function(){e.calls=0,e.triangles=0,e.points=0,e.lines=0},update:function(i,s,n){switch(e.calls++,s){case t.TRIANGLES:e.triangles+=n*(i/3);break;case t.LINES:e.lines+=n*(i/2);break;case t.LINE_STRIP:e.lines+=n*(i-1);break;case t.LINE_LOOP:e.lines+=n*i;break;case t.POINTS:e.points+=n*i}}}}function uU(t,e){return t[0]-e[0]}function pU(t,e){return Math.abs(e[1])-Math.abs(t[1])}function fU(t,e,i){const s={},n=new Float32Array(8),r=new WeakMap,a=new aO,o=[];for(let t=0;t<8;t++)o[t]=[t,0];return{update:function(l,h,c){const d=l.morphTargetInfluences;if(!0===e.isWebGL2){const u=h.morphAttributes.position||h.morphAttributes.normal||h.morphAttributes.color,p=void 0!==u?u.length:0;let f=r.get(h);if(void 0===f||f.count!==p){void 0!==f&&f.texture.dispose();const g=void 0!==h.morphAttributes.position,v=void 0!==h.morphAttributes.normal,y=void 0!==h.morphAttributes.color,S=h.morphAttributes.position||[],x=h.morphAttributes.normal||[],T=h.morphAttributes.color||[];let E=0;!0===g&&(E=1),!0===v&&(E=2),!0===y&&(E=3);let b=h.attributes.position.count*E,w=1;b>e.maxTextureSize&&(w=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const A=new Float32Array(b*w*4*p),C=new hO(A,b,w,p);C.type=qD,C.needsUpdate=!0;const M=4*E;for(let R=0;R<p;R++){const L=S[R],D=x[R],I=T[R],O=b*w*4*R;for(let N=0;N<L.count;N++){const F=N*M;!0===g&&(a.fromBufferAttribute(L,N),A[O+F+0]=a.x,A[O+F+1]=a.y,A[O+F+2]=a.z,A[O+F+3]=0),!0===v&&(a.fromBufferAttribute(D,N),A[O+F+4]=a.x,A[O+F+5]=a.y,A[O+F+6]=a.z,A[O+F+7]=0),!0===y&&(a.fromBufferAttribute(I,N),A[O+F+8]=a.x,A[O+F+9]=a.y,A[O+F+10]=a.z,A[O+F+11]=4===I.itemSize?a.w:1)}}function P(){C.dispose(),r.delete(h),h.removeEventListener("dispose",P)}f={count:p,texture:C,size:new BI(b,w)},r.set(h,f),h.addEventListener("dispose",P)}let m=0;for(let U=0;U<d.length;U++)m+=d[U];const _=h.morphTargetsRelative?1:1-m;c.getUniforms().setValue(t,"morphTargetBaseInfluence",_),c.getUniforms().setValue(t,"morphTargetInfluences",d),c.getUniforms().setValue(t,"morphTargetsTexture",f.texture,i),c.getUniforms().setValue(t,"morphTargetsTextureSize",f.size)}else{const B=void 0===d?0:d.length;let z=s[h.id];if(void 0===z||z.length!==B){z=[];for(let W=0;W<B;W++)z[W]=[W,0];s[h.id]=z}for(let X=0;X<B;X++){const Y=z[X];Y[0]=X,Y[1]=d[X]}z.sort(pU);for(let q=0;q<8;q++)q<B&&z[q][1]?(o[q][0]=z[q][0],o[q][1]=z[q][1]):(o[q][0]=Number.MAX_SAFE_INTEGER,o[q][1]=0);o.sort(uU);const k=h.morphAttributes.position,V=h.morphAttributes.normal;let H=0;for(let j=0;j<8;j++){const $=o[j],K=$[0],Z=$[1];K!==Number.MAX_SAFE_INTEGER&&Z?(k&&h.getAttribute("morphTarget"+j)!==k[K]&&h.setAttribute("morphTarget"+j,k[K]),V&&h.getAttribute("morphNormal"+j)!==V[K]&&h.setAttribute("morphNormal"+j,V[K]),n[j]=Z,H+=Z):(k&&!0===h.hasAttribute("morphTarget"+j)&&h.deleteAttribute("morphTarget"+j),V&&!0===h.hasAttribute("morphNormal"+j)&&h.deleteAttribute("morphNormal"+j),n[j]=0)}const G=h.morphTargetsRelative?1:1-H;c.getUniforms().setValue(t,"morphTargetBaseInfluence",G),c.getUniforms().setValue(t,"morphTargetInfluences",n)}}}}function mU(t,e,i,s){let n=new WeakMap;function r(t){const e=t.target;e.removeEventListener("dispose",r),i.remove(e.instanceMatrix),null!==e.instanceColor&&i.remove(e.instanceColor)}return{update:function(a){const o=s.render.frame,l=a.geometry,h=e.get(a,l);if(n.get(h)!==o&&(e.update(h),n.set(h,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",r)&&a.addEventListener("dispose",r),n.get(a)!==o&&(i.update(a.instanceMatrix,t.ARRAY_BUFFER),null!==a.instanceColor&&i.update(a.instanceColor,t.ARRAY_BUFFER),n.set(a,o))),a.isSkinnedMesh){const t=a.skeleton;n.get(t)!==o&&(t.update(),n.set(t,o))}return h},dispose:function(){n=new WeakMap}}}const _U=new rO,gU=new hO,vU=new cO,yU=new bF,SU=[],xU=[],TU=new Float32Array(16),EU=new Float32Array(9),bU=new Float32Array(4);function wU(t,e,i){const s=t[0];if(s<=0||s>0)return t;const n=e*i;let r=SU[n];if(void 0===r&&(r=new Float32Array(n),SU[n]=r),0!==e){s.toArray(r,0);for(let s=1,n=0;s!==e;++s)n+=i,t[s].toArray(r,n)}return r}function AU(t,e){if(t.length!==e.length)return!1;for(let i=0,s=t.length;i<s;i++)if(t[i]!==e[i])return!1;return!0}function CU(t,e){for(let i=0,s=e.length;i<s;i++)t[i]=e[i]}function MU(t,e){let i=xU[e];void 0===i&&(i=new Int32Array(e),xU[e]=i);for(let s=0;s!==e;++s)i[s]=t.allocateTextureUnit();return i}function PU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1f(this.addr,e),i[0]=e)}function RU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2f(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2fv(this.addr,e),CU(i,e)}}function LU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3f(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else if(void 0!==e.r)i[0]===e.r&&i[1]===e.g&&i[2]===e.b||(t.uniform3f(this.addr,e.r,e.g,e.b),i[0]=e.r,i[1]=e.g,i[2]=e.b);else{if(AU(i,e))return;t.uniform3fv(this.addr,e),CU(i,e)}}function DU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4fv(this.addr,e),CU(i,e)}}function IU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix2fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;bU.set(s),t.uniformMatrix2fv(this.addr,!1,bU),CU(i,s)}}function OU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix3fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;EU.set(s),t.uniformMatrix3fv(this.addr,!1,EU),CU(i,s)}}function NU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix4fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;TU.set(s),t.uniformMatrix4fv(this.addr,!1,TU),CU(i,s)}}function FU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1i(this.addr,e),i[0]=e)}function UU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2i(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2iv(this.addr,e),CU(i,e)}}function BU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3i(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else{if(AU(i,e))return;t.uniform3iv(this.addr,e),CU(i,e)}}function zU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4i(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4iv(this.addr,e),CU(i,e)}}function kU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1ui(this.addr,e),i[0]=e)}function VU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2ui(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2uiv(this.addr,e),CU(i,e)}}function HU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3ui(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else{if(AU(i,e))return;t.uniform3uiv(this.addr,e),CU(i,e)}}function GU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4uiv(this.addr,e),CU(i,e)}}function WU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture2D(e||_U,n)}function XU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture3D(e||vU,n)}function YU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTextureCube(e||yU,n)}function qU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture2DArray(e||gU,n)}function jU(t,e){t.uniform1fv(this.addr,e)}function $U(t,e){const i=wU(e,this.size,2);t.uniform2fv(this.addr,i)}function KU(t,e){const i=wU(e,this.size,3);t.uniform3fv(this.addr,i)}function ZU(t,e){const i=wU(e,this.size,4);t.uniform4fv(this.addr,i)}function QU(t,e){const i=wU(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,i)}function JU(t,e){const i=wU(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,i)}function tB(t,e){const i=wU(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,i)}function eB(t,e){t.uniform1iv(this.addr,e)}function iB(t,e){t.uniform2iv(this.addr,e)}function sB(t,e){t.uniform3iv(this.addr,e)}function nB(t,e){t.uniform4iv(this.addr,e)}function rB(t,e){t.uniform1uiv(this.addr,e)}function aB(t,e){t.uniform2uiv(this.addr,e)}function oB(t,e){t.uniform3uiv(this.addr,e)}function lB(t,e){t.uniform4uiv(this.addr,e)}function hB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture2D(e[t]||_U,r[t])}function cB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture3D(e[t]||vU,r[t])}function dB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTextureCube(e[t]||yU,r[t])}function uB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture2DArray(e[t]||gU,r[t])}class pB{constructor(t,e,i){this.id=t,this.addr=i,this.cache=[],this.setValue=function(t){switch(t){case 5126:return PU;case 35664:return RU;case 35665:return LU;case 35666:return DU;case 35674:return IU;case 35675:return OU;case 35676:return NU;case 5124:case 35670:return FU;case 35667:case 35671:return UU;case 35668:case 35672:return BU;case 35669:case 35673:return zU;case 5125:return kU;case 36294:return VU;case 36295:return HU;case 36296:return GU;case 35678:case 36198:case 36298:case 36306:case 35682:return WU;case 35679:case 36299:case 36307:return XU;case 35680:case 36300:case 36308:case 36293:return YU;case 36289:case 36303:case 36311:case 36292:return qU}}(e.type)}}class fB{constructor(t,e,i){this.id=t,this.addr=i,this.cache=[],this.size=e.size,this.setValue=function(t){switch(t){case 5126:return jU;case 35664:return $U;case 35665:return KU;case 35666:return ZU;case 35674:return QU;case 35675:return JU;case 35676:return tB;case 5124:case 35670:return eB;case 35667:case 35671:return iB;case 35668:case 35672:return sB;case 35669:case 35673:return nB;case 5125:return rB;case 36294:return aB;case 36295:return oB;case 36296:return lB;case 35678:case 36198:case 36298:case 36306:case 35682:return hB;case 35679:case 36299:case 36307:return cB;case 35680:case 36300:case 36308:case 36293:return dB;case 36289:case 36303:case 36311:case 36292:return uB}}(e.type)}}class mB{constructor(t){this.id=t,this.seq=[],this.map={}}setValue(t,e,i){const s=this.seq;for(let n=0,r=s.length;n!==r;++n){const r=s[n];r.setValue(t,e[r.id],i)}}}const _B=/(\w+)(\])?(\[|\.)?/g;function gB(t,e){t.seq.push(e),t.map[e.id]=e}function vB(t,e,i){const s=t.name,n=s.length;for(_B.lastIndex=0;;){const r=_B.exec(s),a=_B.lastIndex;let o=r[1];const l="]"===r[2],h=r[3];if(l&&(o|=0),void 0===h||"["===h&&a+2===n){gB(i,void 0===h?new pB(o,t,e):new fB(o,t,e));break}{let t=i.map[o];void 0===t&&(t=new mB(o),gB(i,t)),i=t}}}class yB{constructor(t,e){this.seq=[],this.map={};const i=t.getProgramParameter(e,t.ACTIVE_UNIFORMS);for(let s=0;s<i;++s){const i=t.getActiveUniform(e,s);vB(i,t.getUniformLocation(e,i.name),this)}}setValue(t,e,i,s){const n=this.map[e];void 0!==n&&n.setValue(t,i,s)}setOptional(t,e,i){const s=e[i];void 0!==s&&this.setValue(t,i,s)}static upload(t,e,i,s){for(let n=0,r=e.length;n!==r;++n){const r=e[n],a=i[r.id];!1!==a.needsUpdate&&r.setValue(t,a.value,s)}}static seqWithValue(t,e){const i=[];for(let s=0,n=t.length;s!==n;++s){const n=t[s];n.id in e&&i.push(n)}return i}}function SB(t,e,i){const s=t.createShader(e);return t.shaderSource(s,i),t.compileShader(s),s}let xB=0;function TB(t,e,i){const s=t.getShaderParameter(e,t.COMPILE_STATUS),n=t.getShaderInfoLog(e).trim();if(s&&""===n)return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const s=parseInt(r[1]);return i.toUpperCase()+"\n\n"+n+"\n\n"+function(t,e){const i=t.split("\n"),s=[],n=Math.max(e-6,0),r=Math.min(e+6,i.length);for(let t=n;t<r;t++){const n=t+1;s.push(`${n===e?">":" "} ${n}: ${i[t]}`)}return s.join("\n")}(t.getShaderSource(e),s)}return n}function EB(t,e){const i=function(t){const e=KI.getPrimaries(KI.workingColorSpace),i=KI.getPrimaries(t);let s;switch(e===i?s="":e===pI&&i===uI?s="LinearDisplayP3ToLinearSRGB":e===uI&&i===pI&&(s="LinearSRGBToLinearDisplayP3"),t){case oI:case hI:return[s,"LinearTransferOETF"];case aI:case lI:return[s,"sRGBTransferOETF"];default:return[s,"LinearTransferOETF"]}}(e);return`vec4 ${t}( vec4 value ) { return ${i[0]}( ${i[1]}( value ) ); }`}function bB(t,e){let i;switch(e){case 1:default:i="Linear";break;case 2:i="Reinhard";break;case 3:i="OptimizedCineon";break;case 4:i="ACESFilmic";break;case 5:i="Custom"}return"vec3 "+t+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}function wB(t){return""!==t}function AB(t,e){const i=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,i).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function CB(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const MB=/^[ \t]*#include +<([\w\d./]+)>/gm;function PB(t){return t.replace(MB,LB)}const RB=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function LB(t,e){let i=FF[e];if(void 0===i){const t=RB.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");i=FF[t]}return PB(i)}const DB=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function IB(t){return t.replace(DB,OB)}function OB(t,e,i,s){let n="";for(let t=parseInt(e);t<parseInt(i);t++)n+=s.replace(/\[\s*i\s*\]/g,"[ "+t+" ]").replace(/UNROLLED_LOOP_INDEX/g,t);return n}function NB(t){let e="precision "+t.precision+" float;\nprecision "+t.precision+" int;";return"highp"===t.precision?e+="\n#define HIGH_PRECISION":"mediump"===t.precision?e+="\n#define MEDIUM_PRECISION":"lowp"===t.precision&&(e+="\n#define LOW_PRECISION"),e}function FB(t,e,i,s){const n=t.getContext(),r=i.defines;let a=i.vertexShader,o=i.fragmentShader;const l=function(t){let e="SHADOWMAP_TYPE_BASIC";return 1===t.shadowMapType?e="SHADOWMAP_TYPE_PCF":2===t.shadowMapType?e="SHADOWMAP_TYPE_PCF_SOFT":3===t.shadowMapType&&(e="SHADOWMAP_TYPE_VSM"),e}(i),h=function(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case LD:case DD:e="ENVMAP_TYPE_CUBE";break;case ID:e="ENVMAP_TYPE_CUBE_UV"}return e}(i),c=function(t){let e="ENVMAP_MODE_REFLECTION";t.envMap&&t.envMapMode===DD&&(e="ENVMAP_MODE_REFRACTION");return e}(i),d=function(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case 0:e="ENVMAP_BLENDING_MULTIPLY";break;case 1:e="ENVMAP_BLENDING_MIX";break;case 2:e="ENVMAP_BLENDING_ADD"}return e}(i),u=function(t){const e=t.envMapCubeUVHeight;if(null===e)return null;const i=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,i),112)),texelHeight:s,maxMip:i}}(i),p=i.isWebGL2?"":function(t){return[t.extensionDerivatives||t.envMapCubeUVHeight||t.bumpMap||t.normalMapTangentSpace||t.clearcoatNormalMap||t.flatShading||"physical"===t.shaderID?"#extension GL_OES_standard_derivatives : enable":"",(t.extensionFragDepth||t.logarithmicDepthBuffer)&&t.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",t.extensionDrawBuffers&&t.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(t.extensionShaderTextureLOD||t.envMap||t.transmission)&&t.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(wB).join("\n")}(i),f=function(t){const e=[];for(const i in t){const s=t[i];!1!==s&&e.push("#define "+i+" "+s)}return e.join("\n")}(r),m=n.createProgram();let _,g,v=i.glslVersion?"#version "+i.glslVersion+"\n":"";i.isRawShaderMaterial?(_=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f].filter(wB).join("\n"),_.length>0&&(_+="\n"),g=[p,"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f].filter(wB).join("\n"),g.length>0&&(g+="\n")):(_=[NB(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f,i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+c:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&!1===i.flatShading?"#define USE_MORPHNORMALS":"",i.morphColors&&i.isWebGL2?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.useLegacyLights?"#define LEGACY_LIGHTS":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(wB).join("\n"),g=[p,NB(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+h:"",i.envMap?"#define "+c:"",i.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.useLegacyLights?"#define LEGACY_LIGHTS":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==i.toneMapping?"#define TONE_MAPPING":"",0!==i.toneMapping?FF.tonemapping_pars_fragment:"",0!==i.toneMapping?bB("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",FF.colorspace_pars_fragment,EB("linearToOutputTexel",i.outputColorSpace),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(wB).join("\n")),a=PB(a),a=AB(a,i),a=CB(a,i),o=PB(o),o=AB(o,i),o=CB(o,i),a=IB(a),o=IB(o),i.isWebGL2&&!0!==i.isRawShaderMaterial&&(v="#version 300 es\n",_=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+_,g=["#define varying in",i.glslVersion===EI?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===EI?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+g);const y=v+_+a,S=v+g+o,x=SB(n,n.VERTEX_SHADER,y),T=SB(n,n.FRAGMENT_SHADER,S);if(n.attachShader(m,x),n.attachShader(m,T),void 0!==i.index0AttributeName?n.bindAttribLocation(m,0,i.index0AttributeName):!0===i.morphTargets&&n.bindAttribLocation(m,0,"position"),n.linkProgram(m),t.debug.checkShaderErrors){const e=n.getProgramInfoLog(m).trim(),i=n.getShaderInfoLog(x).trim(),s=n.getShaderInfoLog(T).trim();let r=!0,a=!0;if(!1===n.getProgramParameter(m,n.LINK_STATUS))if(r=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(n,m,x,T);else{TB(n,x,"vertex"),TB(n,T,"fragment")}else""!==e||""!==i&&""!==s||(a=!1);a&&(this.diagnostics={runnable:r,programLog:e,vertexShader:{log:i,prefix:_},fragmentShader:{log:s,prefix:g}})}let E,b;return n.deleteShader(x),n.deleteShader(T),this.getUniforms=function(){return void 0===E&&(E=new yB(n,m)),E},this.getAttributes=function(){return void 0===b&&(b=function(t,e){const i={},s=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let n=0;n<s;n++){const s=t.getActiveAttrib(e,n),r=s.name;let a=1;s.type===t.FLOAT_MAT2&&(a=2),s.type===t.FLOAT_MAT3&&(a=3),s.type===t.FLOAT_MAT4&&(a=4),i[r]={type:s.type,location:t.getAttribLocation(e,r),locationSize:a}}return i}(n,m)),b},this.destroy=function(){s.releaseStatesOfProgram(this),n.deleteProgram(m),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=xB++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=x,this.fragmentShader=T,this}let UB=0;class BB{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,i=t.fragmentShader,s=this._getShaderStage(e),n=this._getShaderStage(i),r=this._getShaderCacheForMaterial(t);return!1===r.has(s)&&(r.add(s),s.usedTimes++),!1===r.has(n)&&(r.add(n),n.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const t of e)t.usedTimes--,0===t.usedTimes&&this.shaderCache.delete(t.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){const e=this.materialCache;let i=e.get(t);return void 0===i&&(i=new Set,e.set(t,i)),i}_getShaderStage(t){const e=this.shaderCache;let i=e.get(t);return void 0===i&&(i=new zB(t),e.set(t,i)),i}}class zB{constructor(t){this.id=UB++,this.code=t,this.usedTimes=0}}function kB(t,e,i,s,n,r,a){const o=new JO,l=new BB,h=[],c=n.isWebGL2,d=n.logarithmicDepthBuffer,u=n.vertexTextures;let p=n.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(t){return 0===t?"uv":`uv${t}`}return{getParameters:function(r,o,h,_,g){const v=_.fog,y=g.geometry,S=r.isMeshStandardMaterial?_.environment:null,x=(r.isMeshStandardMaterial?i:e).get(r.envMap||S),T=x&&x.mapping===ID?x.image.height:null,E=f[r.type];null!==r.precision&&(p=n.getMaxPrecision(r.precision),r.precision);const b=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,w=void 0!==b?b.length:0;let A,C,M,P,R=0;if(void 0!==y.morphAttributes.position&&(R=1),void 0!==y.morphAttributes.normal&&(R=2),void 0!==y.morphAttributes.color&&(R=3),E){const t=BF[E];A=t.vertexShader,C=t.fragmentShader}else A=r.vertexShader,C=r.fragmentShader,l.update(r),M=l.getVertexShaderID(r),P=l.getFragmentShaderID(r);const L=t.getRenderTarget(),D=!0===g.isInstancedMesh,I=!!r.map,O=!!r.matcap,N=!!x,F=!!r.aoMap,U=!!r.lightMap,B=!!r.bumpMap,z=!!r.normalMap,k=!!r.displacementMap,V=!!r.emissiveMap,H=!!r.metalnessMap,G=!!r.roughnessMap,W=r.anisotropy>0,X=r.clearcoat>0,Y=r.iridescence>0,q=r.sheen>0,j=r.transmission>0,$=W&&!!r.anisotropyMap,K=X&&!!r.clearcoatMap,Z=X&&!!r.clearcoatNormalMap,Q=X&&!!r.clearcoatRoughnessMap,J=Y&&!!r.iridescenceMap,tt=Y&&!!r.iridescenceThicknessMap,et=q&&!!r.sheenColorMap,it=q&&!!r.sheenRoughnessMap,st=!!r.specularMap,nt=!!r.specularColorMap,rt=!!r.specularIntensityMap,at=j&&!!r.transmissionMap,ot=j&&!!r.thicknessMap,lt=!!r.gradientMap,ht=!!r.alphaMap,ct=r.alphaTest>0,dt=!!r.alphaHash,ut=!!r.extensions,pt=!!y.attributes.uv1,ft=!!y.attributes.uv2,mt=!!y.attributes.uv3;let _t=0;return r.toneMapped&&(null!==L&&!0!==L.isXRRenderTarget||(_t=t.toneMapping)),{isWebGL2:c,shaderID:E,shaderType:r.type,shaderName:r.name,vertexShader:A,fragmentShader:C,defines:r.defines,customVertexShaderID:M,customFragmentShaderID:P,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:p,instancing:D,instancingColor:D&&null!==g.instanceColor,supportsVertexTextures:u,outputColorSpace:null===L?t.outputColorSpace:!0===L.isXRRenderTarget?L.texture.colorSpace:oI,map:I,matcap:O,envMap:N,envMapMode:N&&x.mapping,envMapCubeUVHeight:T,aoMap:F,lightMap:U,bumpMap:B,normalMap:z,displacementMap:u&&k,emissiveMap:V,normalMapObjectSpace:z&&1===r.normalMapType,normalMapTangentSpace:z&&0===r.normalMapType,metalnessMap:H,roughnessMap:G,anisotropy:W,anisotropyMap:$,clearcoat:X,clearcoatMap:K,clearcoatNormalMap:Z,clearcoatRoughnessMap:Q,iridescence:Y,iridescenceMap:J,iridescenceThicknessMap:tt,sheen:q,sheenColorMap:et,sheenRoughnessMap:it,specularMap:st,specularColorMap:nt,specularIntensityMap:rt,transmission:j,transmissionMap:at,thicknessMap:ot,gradientMap:lt,opaque:!1===r.transparent&&1===r.blending,alphaMap:ht,alphaTest:ct,alphaHash:dt,combine:r.combine,mapUv:I&&m(r.map.channel),aoMapUv:F&&m(r.aoMap.channel),lightMapUv:U&&m(r.lightMap.channel),bumpMapUv:B&&m(r.bumpMap.channel),normalMapUv:z&&m(r.normalMap.channel),displacementMapUv:k&&m(r.displacementMap.channel),emissiveMapUv:V&&m(r.emissiveMap.channel),metalnessMapUv:H&&m(r.metalnessMap.channel),roughnessMapUv:G&&m(r.roughnessMap.channel),anisotropyMapUv:$&&m(r.anisotropyMap.channel),clearcoatMapUv:K&&m(r.clearcoatMap.channel),clearcoatNormalMapUv:Z&&m(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Q&&m(r.clearcoatRoughnessMap.channel),iridescenceMapUv:J&&m(r.iridescenceMap.channel),iridescenceThicknessMapUv:tt&&m(r.iridescenceThicknessMap.channel),sheenColorMapUv:et&&m(r.sheenColorMap.channel),sheenRoughnessMapUv:it&&m(r.sheenRoughnessMap.channel),specularMapUv:st&&m(r.specularMap.channel),specularColorMapUv:nt&&m(r.specularColorMap.channel),specularIntensityMapUv:rt&&m(r.specularIntensityMap.channel),transmissionMapUv:at&&m(r.transmissionMap.channel),thicknessMapUv:ot&&m(r.thicknessMap.channel),alphaMapUv:ht&&m(r.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(z||W),vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,vertexUv1s:pt,vertexUv2s:ft,vertexUv3s:mt,pointsUvs:!0===g.isPoints&&!!y.attributes.uv&&(I||ht),fog:!!v,useFog:!0===r.fog,fogExp2:v&&v.isFogExp2,flatShading:!0===r.flatShading,sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:d,skinning:!0===g.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:w,morphTextureStride:R,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:r.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:_t,useLegacyLights:t._useLegacyLights,decodeVideoTexture:I&&!0===r.map.isVideoTexture&&KI.getTransfer(r.map.colorSpace)===dI,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionDerivatives:ut&&!0===r.extensions.derivatives,extensionFragDepth:ut&&!0===r.extensions.fragDepth,extensionDrawBuffers:ut&&!0===r.extensions.drawBuffers,extensionShaderTextureLOD:ut&&!0===r.extensions.shaderTextureLOD,rendererExtensionFragDepth:c||s.has("EXT_frag_depth"),rendererExtensionDrawBuffers:c||s.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:c||s.has("EXT_shader_texture_lod"),customProgramCacheKey:r.customProgramCacheKey()}},getProgramCacheKey:function(e){const i=[];if(e.shaderID?i.push(e.shaderID):(i.push(e.customVertexShaderID),i.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)i.push(t),i.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(i,e),function(t,e){o.disableAll(),e.isWebGL2&&o.enable(0);e.supportsVertexTextures&&o.enable(1);e.instancing&&o.enable(2);e.instancingColor&&o.enable(3);e.matcap&&o.enable(4);e.envMap&&o.enable(5);e.normalMapObjectSpace&&o.enable(6);e.normalMapTangentSpace&&o.enable(7);e.clearcoat&&o.enable(8);e.iridescence&&o.enable(9);e.alphaTest&&o.enable(10);e.vertexColors&&o.enable(11);e.vertexAlphas&&o.enable(12);e.vertexUv1s&&o.enable(13);e.vertexUv2s&&o.enable(14);e.vertexUv3s&&o.enable(15);e.vertexTangents&&o.enable(16);e.anisotropy&&o.enable(17);t.push(o.mask),o.disableAll(),e.fog&&o.enable(0);e.useFog&&o.enable(1);e.flatShading&&o.enable(2);e.logarithmicDepthBuffer&&o.enable(3);e.skinning&&o.enable(4);e.morphTargets&&o.enable(5);e.morphNormals&&o.enable(6);e.morphColors&&o.enable(7);e.premultipliedAlpha&&o.enable(8);e.shadowMapEnabled&&o.enable(9);e.useLegacyLights&&o.enable(10);e.doubleSided&&o.enable(11);e.flipSided&&o.enable(12);e.useDepthPacking&&o.enable(13);e.dithering&&o.enable(14);e.transmission&&o.enable(15);e.sheen&&o.enable(16);e.opaque&&o.enable(17);e.pointsUvs&&o.enable(18);e.decodeVideoTexture&&o.enable(19);t.push(o.mask)}(i,e),i.push(t.outputColorSpace)),i.push(e.customProgramCacheKey),i.join()},getUniforms:function(t){const e=f[t.type];let i;if(e){const t=BF[e];i=vF.clone(t.uniforms)}else i=t.uniforms;return i},acquireProgram:function(e,i){let s;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(e.cacheKey===i){s=e,++s.usedTimes;break}}return void 0===s&&(s=new FB(t,i,e,r),h.push(s)),s},releaseProgram:function(t){if(0===--t.usedTimes){const e=h.indexOf(t);h[e]=h[h.length-1],h.pop(),t.destroy()}},releaseShaderCache:function(t){l.remove(t)},programs:h,dispose:function(){l.dispose()}}}function VB(){let t=new WeakMap;return{get:function(e){let i=t.get(e);return void 0===i&&(i={},t.set(e,i)),i},remove:function(e){t.delete(e)},update:function(e,i,s){t.get(e)[i]=s},dispose:function(){t=new WeakMap}}}function HB(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function GB(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function WB(){const t=[];let e=0;const i=[],s=[],n=[];function r(i,s,n,r,a,o){let l=t[e];return void 0===l?(l={id:i.id,object:i,geometry:s,material:n,groupOrder:r,renderOrder:i.renderOrder,z:a,group:o},t[e]=l):(l.id=i.id,l.object=i,l.geometry=s,l.material=n,l.groupOrder=r,l.renderOrder=i.renderOrder,l.z=a,l.group=o),e++,l}return{opaque:i,transmissive:s,transparent:n,init:function(){e=0,i.length=0,s.length=0,n.length=0},push:function(t,e,a,o,l,h){const c=r(t,e,a,o,l,h);a.transmission>0?s.push(c):!0===a.transparent?n.push(c):i.push(c)},unshift:function(t,e,a,o,l,h){const c=r(t,e,a,o,l,h);a.transmission>0?s.unshift(c):!0===a.transparent?n.unshift(c):i.unshift(c)},finish:function(){for(let i=e,s=t.length;i<s;i++){const e=t[i];if(null===e.id)break;e.id=null,e.object=null,e.geometry=null,e.material=null,e.group=null}},sort:function(t,e){i.length>1&&i.sort(t||HB),s.length>1&&s.sort(e||GB),n.length>1&&n.sort(e||GB)}}}function XB(){let t=new WeakMap;return{get:function(e,i){const s=t.get(e);let n;return void 0===s?(n=new WB,t.set(e,[n])):i>=s.length?(n=new WB,s.push(n)):n=s[i],n},dispose:function(){t=new WeakMap}}}function YB(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":i={direction:new uO,color:new DN};break;case"SpotLight":i={position:new uO,direction:new uO,color:new DN,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new uO,color:new DN,distance:0,decay:0};break;case"HemisphereLight":i={direction:new uO,skyColor:new DN,groundColor:new DN};break;case"RectAreaLight":i={color:new DN,position:new uO,halfWidth:new uO,halfHeight:new uO}}return t[e.id]=i,i}}}let qB=0;function jB(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function $B(t,e){const i=new YB,s=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":case"SpotLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new BI};break;case"PointLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new BI,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=i,i}}}(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let t=0;t<9;t++)n.probe.push(new uO);const r=new uO,a=new HO,o=new HO;return{setup:function(r,a){let o=0,l=0,h=0;for(let t=0;t<9;t++)n.probe[t].set(0,0,0);let c=0,d=0,u=0,p=0,f=0,m=0,_=0,g=0,v=0,y=0,S=0;r.sort(jB);const x=!0===a?Math.PI:1;for(let t=0,e=r.length;t<e;t++){const e=r[t],a=e.color,T=e.intensity,E=e.distance,b=e.shadow&&e.shadow.map?e.shadow.map.texture:null;if(e.isAmbientLight)o+=a.r*T*x,l+=a.g*T*x,h+=a.b*T*x;else if(e.isLightProbe){for(let t=0;t<9;t++)n.probe[t].addScaledVector(e.sh.coefficients[t],T);S++}else if(e.isDirectionalLight){const t=i.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*x),e.castShadow){const t=e.shadow,i=s.get(e);i.shadowBias=t.bias,i.shadowNormalBias=t.normalBias,i.shadowRadius=t.radius,i.shadowMapSize=t.mapSize,n.directionalShadow[c]=i,n.directionalShadowMap[c]=b,n.directionalShadowMatrix[c]=e.shadow.matrix,m++}n.directional[c]=t,c++}else if(e.isSpotLight){const t=i.get(e);t.position.setFromMatrixPosition(e.matrixWorld),t.color.copy(a).multiplyScalar(T*x),t.distance=E,t.coneCos=Math.cos(e.angle),t.penumbraCos=Math.cos(e.angle*(1-e.penumbra)),t.decay=e.decay,n.spot[u]=t;const r=e.shadow;if(e.map&&(n.spotLightMap[v]=e.map,v++,r.updateMatrices(e),e.castShadow&&y++),n.spotLightMatrix[u]=r.matrix,e.castShadow){const t=s.get(e);t.shadowBias=r.bias,t.shadowNormalBias=r.normalBias,t.shadowRadius=r.radius,t.shadowMapSize=r.mapSize,n.spotShadow[u]=t,n.spotShadowMap[u]=b,g++}u++}else if(e.isRectAreaLight){const t=i.get(e);t.color.copy(a).multiplyScalar(T),t.halfWidth.set(.5*e.width,0,0),t.halfHeight.set(0,.5*e.height,0),n.rectArea[p]=t,p++}else if(e.isPointLight){const t=i.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*x),t.distance=e.distance,t.decay=e.decay,e.castShadow){const t=e.shadow,i=s.get(e);i.shadowBias=t.bias,i.shadowNormalBias=t.normalBias,i.shadowRadius=t.radius,i.shadowMapSize=t.mapSize,i.shadowCameraNear=t.camera.near,i.shadowCameraFar=t.camera.far,n.pointShadow[d]=i,n.pointShadowMap[d]=b,n.pointShadowMatrix[d]=e.shadow.matrix,_++}n.point[d]=t,d++}else if(e.isHemisphereLight){const t=i.get(e);t.skyColor.copy(e.color).multiplyScalar(T*x),t.groundColor.copy(e.groundColor).multiplyScalar(T*x),n.hemi[f]=t,f++}}p>0&&(e.isWebGL2||!0===t.has("OES_texture_float_linear")?(n.rectAreaLTC1=UF.LTC_FLOAT_1,n.rectAreaLTC2=UF.LTC_FLOAT_2):!0===t.has("OES_texture_half_float_linear")&&(n.rectAreaLTC1=UF.LTC_HALF_1,n.rectAreaLTC2=UF.LTC_HALF_2)),n.ambient[0]=o,n.ambient[1]=l,n.ambient[2]=h;const T=n.hash;T.directionalLength===c&&T.pointLength===d&&T.spotLength===u&&T.rectAreaLength===p&&T.hemiLength===f&&T.numDirectionalShadows===m&&T.numPointShadows===_&&T.numSpotShadows===g&&T.numSpotMaps===v&&T.numLightProbes===S||(n.directional.length=c,n.spot.length=u,n.rectArea.length=p,n.point.length=d,n.hemi.length=f,n.directionalShadow.length=m,n.directionalShadowMap.length=m,n.pointShadow.length=_,n.pointShadowMap.length=_,n.spotShadow.length=g,n.spotShadowMap.length=g,n.directionalShadowMatrix.length=m,n.pointShadowMatrix.length=_,n.spotLightMatrix.length=g+v-y,n.spotLightMap.length=v,n.numSpotLightShadowsWithMaps=y,n.numLightProbes=S,T.directionalLength=c,T.pointLength=d,T.spotLength=u,T.rectAreaLength=p,T.hemiLength=f,T.numDirectionalShadows=m,T.numPointShadows=_,T.numSpotShadows=g,T.numSpotMaps=v,T.numLightProbes=S,n.version=qB++)},setupView:function(t,e){let i=0,s=0,l=0,h=0,c=0;const d=e.matrixWorldInverse;for(let e=0,u=t.length;e<u;e++){const u=t[e];if(u.isDirectionalLight){const t=n.directional[i];t.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(d),i++}else if(u.isSpotLight){const t=n.spot[l];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),t.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(d),l++}else if(u.isRectAreaLight){const t=n.rectArea[h];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),o.identity(),a.copy(u.matrixWorld),a.premultiply(d),o.extractRotation(a),t.halfWidth.set(.5*u.width,0,0),t.halfHeight.set(0,.5*u.height,0),t.halfWidth.applyMatrix4(o),t.halfHeight.applyMatrix4(o),h++}else if(u.isPointLight){const t=n.point[s];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),s++}else if(u.isHemisphereLight){const t=n.hemi[c];t.direction.setFromMatrixPosition(u.matrixWorld),t.direction.transformDirection(d),c++}}},state:n}}function KB(t,e){const i=new $B(t,e),s=[],n=[];return{init:function(){s.length=0,n.length=0},state:{lightsArray:s,shadowsArray:n,lights:i},setupLights:function(t){i.setup(s,t)},setupLightsView:function(t){i.setupView(s,t)},pushLight:function(t){s.push(t)},pushShadow:function(t){n.push(t)}}}function ZB(t,e){let i=new WeakMap;return{get:function(s,n=0){const r=i.get(s);let a;return void 0===r?(a=new KB(t,e),i.set(s,[a])):n>=r.length?(a=new KB(t,e),r.push(a)):a=r[n],a},dispose:function(){i=new WeakMap}}}class QB extends CN{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class JB extends CN{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function tz(t,e,i){let s=new DF;const n=new BI,r=new BI,a=new aO,o=new QB({depthPacking:3201}),l=new JB,h={},c=i.maxTextureSize,d={[fD]:1,[mD]:0,[_D]:2},u=new yF({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new BI},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=u.clone();p.defines.HORIZONTAL_PASS=1;const f=new jN;f.setAttribute("position",new UN(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new uF(f,u),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let g=this.type;function v(i,s){const r=e.update(m);u.defines.VSM_SAMPLES!==i.blurSamples&&(u.defines.VSM_SAMPLES=i.blurSamples,p.defines.VSM_SAMPLES=i.blurSamples,u.needsUpdate=!0,p.needsUpdate=!0),null===i.mapPass&&(i.mapPass=new lO(n.x,n.y)),u.uniforms.shadow_pass.value=i.map.texture,u.uniforms.resolution.value=i.mapSize,u.uniforms.radius.value=i.radius,t.setRenderTarget(i.mapPass),t.clear(),t.renderBufferDirect(s,null,r,u,m,null),p.uniforms.shadow_pass.value=i.mapPass.texture,p.uniforms.resolution.value=i.mapSize,p.uniforms.radius.value=i.radius,t.setRenderTarget(i.map),t.clear(),t.renderBufferDirect(s,null,r,p,m,null)}function y(e,i,s,n){let r=null;const a=!0===s.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)r=a;else if(r=!0===s.isPointLight?l:o,t.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0){const t=r.uuid,e=i.uuid;let s=h[t];void 0===s&&(s={},h[t]=s);let n=s[e];void 0===n&&(n=r.clone(),s[e]=n),r=n}if(r.visible=i.visible,r.wireframe=i.wireframe,r.side=3===n?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:d[i.side],r.alphaMap=i.alphaMap,r.alphaTest=i.alphaTest,r.map=i.map,r.clipShadows=i.clipShadows,r.clippingPlanes=i.clippingPlanes,r.clipIntersection=i.clipIntersection,r.displacementMap=i.displacementMap,r.displacementScale=i.displacementScale,r.displacementBias=i.displacementBias,r.wireframeLinewidth=i.wireframeLinewidth,r.linewidth=i.linewidth,!0===s.isPointLight&&!0===r.isMeshDistanceMaterial){t.properties.get(r).light=s}return r}function S(i,n,r,a,o){if(!1===i.visible)return;if(i.layers.test(n.layers)&&(i.isMesh||i.isLine||i.isPoints)&&(i.castShadow||i.receiveShadow&&3===o)&&(!i.frustumCulled||s.intersectsObject(i))){i.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,i.matrixWorld);const s=e.update(i),n=i.material;if(Array.isArray(n)){const e=s.groups;for(let l=0,h=e.length;l<h;l++){const h=e[l],c=n[h.materialIndex];if(c&&c.visible){const e=y(i,c,a,o);t.renderBufferDirect(r,null,s,e,i,h)}}}else if(n.visible){const e=y(i,n,a,o);t.renderBufferDirect(r,null,s,e,i,null)}}const l=i.children;for(let t=0,e=l.length;t<e;t++)S(l[t],n,r,a,o)}this.render=function(e,i,o){if(!1===_.enabled)return;if(!1===_.autoUpdate&&!1===_.needsUpdate)return;if(0===e.length)return;const l=t.getRenderTarget(),h=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),u=t.state;u.setBlending(0),u.buffers.color.setClear(1,1,1,1),u.buffers.depth.setTest(!0),u.setScissorTest(!1);const p=3!==g&&3===this.type,f=3===g&&3!==this.type;for(let l=0,h=e.length;l<h;l++){const h=e[l],d=h.shadow;if(void 0===d)continue;if(!1===d.autoUpdate&&!1===d.needsUpdate)continue;n.copy(d.mapSize);const m=d.getFrameExtents();if(n.multiply(m),r.copy(d.mapSize),(n.x>c||n.y>c)&&(n.x>c&&(r.x=Math.floor(c/m.x),n.x=r.x*m.x,d.mapSize.x=r.x),n.y>c&&(r.y=Math.floor(c/m.y),n.y=r.y*m.y,d.mapSize.y=r.y)),null===d.map||!0===p||!0===f){const t=3!==this.type?{minFilter:UD,magFilter:UD}:{};null!==d.map&&d.map.dispose(),d.map=new lO(n.x,n.y,t),d.map.texture.name=h.name+".shadowMap",d.camera.updateProjectionMatrix()}t.setRenderTarget(d.map),t.clear();const _=d.getViewportCount();for(let t=0;t<_;t++){const e=d.getViewport(t);a.set(r.x*e.x,r.y*e.y,r.x*e.z,r.y*e.w),u.viewport(a),d.updateMatrices(h,t),s=d.getFrustum(),S(i,o,d.camera,h,this.type)}!0!==d.isPointLightShadow&&3===this.type&&v(d,o),d.needsUpdate=!1}g=this.type,_.needsUpdate=!1,t.setRenderTarget(l,h,d)}}function ez(t,e,i){const s=i.isWebGL2;const n=new function(){let e=!1;const i=new aO;let s=null;const n=new aO(0,0,0,0);return{setMask:function(i){s===i||e||(t.colorMask(i,i,i,i),s=i)},setLocked:function(t){e=t},setClear:function(e,s,r,a,o){!0===o&&(e*=a,s*=a,r*=a),i.set(e,s,r,a),!1===n.equals(i)&&(t.clearColor(e,s,r,a),n.copy(i))},reset:function(){e=!1,s=null,n.set(-1,0,0,0)}}},r=new function(){let e=!1,i=null,s=null,n=null;return{setTest:function(e){e?k(t.DEPTH_TEST):V(t.DEPTH_TEST)},setMask:function(s){i===s||e||(t.depthMask(s),i=s)},setFunc:function(e){if(s!==e){switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}s=e}},setLocked:function(t){e=t},setClear:function(e){n!==e&&(t.clearDepth(e),n=e)},reset:function(){e=!1,i=null,s=null,n=null}}},a=new function(){let e=!1,i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null;return{setTest:function(i){e||(i?k(t.STENCIL_TEST):V(t.STENCIL_TEST))},setMask:function(s){i===s||e||(t.stencilMask(s),i=s)},setFunc:function(e,i,a){s===e&&n===i&&r===a||(t.stencilFunc(e,i,a),s=e,n=i,r=a)},setOp:function(e,i,s){a===e&&o===i&&l===s||(t.stencilOp(e,i,s),a=e,o=i,l=s)},setLocked:function(t){e=t},setClear:function(e){h!==e&&(t.clearStencil(e),h=e)},reset:function(){e=!1,i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null}}},o=new WeakMap,l=new WeakMap;let h={},c={},d=new WeakMap,u=[],p=null,f=!1,m=null,_=null,g=null,v=null,y=null,S=null,x=null,T=!1,E=null,b=null,w=null,A=null,C=null;const M=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let P=!1,R=0;const L=t.getParameter(t.VERSION);-1!==L.indexOf("WebGL")?(R=parseFloat(/^WebGL (\d)/.exec(L)[1]),P=R>=1):-1!==L.indexOf("OpenGL ES")&&(R=parseFloat(/^OpenGL ES (\d)/.exec(L)[1]),P=R>=2);let D=null,I={};const O=t.getParameter(t.SCISSOR_BOX),N=t.getParameter(t.VIEWPORT),F=(new aO).fromArray(O),U=(new aO).fromArray(N);function B(e,i,n,r){const a=new Uint8Array(4),o=t.createTexture();t.bindTexture(e,o),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let o=0;o<n;o++)!s||e!==t.TEXTURE_3D&&e!==t.TEXTURE_2D_ARRAY?t.texImage2D(i+o,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,a):t.texImage3D(i,0,t.RGBA,1,1,r,0,t.RGBA,t.UNSIGNED_BYTE,a);return o}const z={};function k(e){!0!==h[e]&&(t.enable(e),h[e]=!0)}function V(e){!1!==h[e]&&(t.disable(e),h[e]=!1)}z[t.TEXTURE_2D]=B(t.TEXTURE_2D,t.TEXTURE_2D,1),z[t.TEXTURE_CUBE_MAP]=B(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),s&&(z[t.TEXTURE_2D_ARRAY]=B(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),z[t.TEXTURE_3D]=B(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),n.setClear(0,0,0,1),r.setClear(1),a.setClear(0),k(t.DEPTH_TEST),r.setFunc(3),X(!1),Y(1),k(t.CULL_FACE),W(0);const H={[gD]:t.FUNC_ADD,[vD]:t.FUNC_SUBTRACT,[yD]:t.FUNC_REVERSE_SUBTRACT};if(s)H[103]=t.MIN,H[104]=t.MAX;else{const t=e.get("EXT_blend_minmax");null!==t&&(H[103]=t.MIN_EXT,H[104]=t.MAX_EXT)}const G={[SD]:t.ZERO,[xD]:t.ONE,[TD]:t.SRC_COLOR,[bD]:t.SRC_ALPHA,[RD]:t.SRC_ALPHA_SATURATE,[MD]:t.DST_COLOR,[AD]:t.DST_ALPHA,[ED]:t.ONE_MINUS_SRC_COLOR,[wD]:t.ONE_MINUS_SRC_ALPHA,[PD]:t.ONE_MINUS_DST_COLOR,[CD]:t.ONE_MINUS_DST_ALPHA};function W(e,i,s,n,r,a,o,l){if(0!==e){if(!1===f&&(k(t.BLEND),f=!0),5===e)r=r||i,a=a||s,o=o||n,i===_&&r===y||(t.blendEquationSeparate(H[i],H[r]),_=i,y=r),s===g&&n===v&&a===S&&o===x||(t.blendFuncSeparate(G[s],G[n],G[a],G[o]),g=s,v=n,S=a,x=o),m=e,T=!1;else if(e!==m||l!==T){if(_===gD&&y===gD||(t.blendEquation(t.FUNC_ADD),_=gD,y=gD),l)switch(e){case 1:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.ONE,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA)}else switch(e){case 1:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFunc(t.ZERO,t.SRC_COLOR)}g=null,v=null,S=null,x=null,m=e,T=l}}else!0===f&&(V(t.BLEND),f=!1)}function X(e){E!==e&&(e?t.frontFace(t.CW):t.frontFace(t.CCW),E=e)}function Y(e){0!==e?(k(t.CULL_FACE),e!==b&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):V(t.CULL_FACE),b=e}function q(e,i,s){e?(k(t.POLYGON_OFFSET_FILL),A===i&&C===s||(t.polygonOffset(i,s),A=i,C=s)):V(t.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:r,stencil:a},enable:k,disable:V,bindFramebuffer:function(e,i){return c[e]!==i&&(t.bindFramebuffer(e,i),c[e]=i,s&&(e===t.DRAW_FRAMEBUFFER&&(c[t.FRAMEBUFFER]=i),e===t.FRAMEBUFFER&&(c[t.DRAW_FRAMEBUFFER]=i)),!0)},drawBuffers:function(s,n){let r=u,a=!1;if(s)if(r=d.get(n),void 0===r&&(r=[],d.set(n,r)),s.isWebGLMultipleRenderTargets){const e=s.texture;if(r.length!==e.length||r[0]!==t.COLOR_ATTACHMENT0){for(let i=0,s=e.length;i<s;i++)r[i]=t.COLOR_ATTACHMENT0+i;r.length=e.length,a=!0}}else r[0]!==t.COLOR_ATTACHMENT0&&(r[0]=t.COLOR_ATTACHMENT0,a=!0);else r[0]!==t.BACK&&(r[0]=t.BACK,a=!0);a&&(i.isWebGL2?t.drawBuffers(r):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(r))},useProgram:function(e){return p!==e&&(t.useProgram(e),p=e,!0)},setBlending:W,setMaterial:function(e,i){2===e.side?V(t.CULL_FACE):k(t.CULL_FACE);let s=1===e.side;i&&(s=!s),X(s),1===e.blending&&!1===e.transparent?W(0):W(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),r.setFunc(e.depthFunc),r.setTest(e.depthTest),r.setMask(e.depthWrite),n.setMask(e.colorWrite);const o=e.stencilWrite;a.setTest(o),o&&(a.setMask(e.stencilWriteMask),a.setFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),a.setOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),q(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage?k(t.SAMPLE_ALPHA_TO_COVERAGE):V(t.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:X,setCullFace:Y,setLineWidth:function(e){e!==w&&(P&&t.lineWidth(e),w=e)},setPolygonOffset:q,setScissorTest:function(e){e?k(t.SCISSOR_TEST):V(t.SCISSOR_TEST)},activeTexture:function(e){void 0===e&&(e=t.TEXTURE0+M-1),D!==e&&(t.activeTexture(e),D=e)},bindTexture:function(e,i,s){void 0===s&&(s=null===D?t.TEXTURE0+M-1:D);let n=I[s];void 0===n&&(n={type:void 0,texture:void 0},I[s]=n),n.type===e&&n.texture===i||(D!==s&&(t.activeTexture(s),D=s),t.bindTexture(e,i||z[e]),n.type=e,n.texture=i)},unbindTexture:function(){const e=I[D];void 0!==e&&void 0!==e.type&&(t.bindTexture(e.type,null),e.type=void 0,e.texture=void 0)},compressedTexImage2D:function(){try{t.compressedTexImage2D.apply(t,arguments)}catch(t){}},compressedTexImage3D:function(){try{t.compressedTexImage3D.apply(t,arguments)}catch(t){}},texImage2D:function(){try{t.texImage2D.apply(t,arguments)}catch(t){}},texImage3D:function(){try{t.texImage3D.apply(t,arguments)}catch(t){}},updateUBOMapping:function(e,i){let s=l.get(i);void 0===s&&(s=new WeakMap,l.set(i,s));let n=s.get(e);void 0===n&&(n=t.getUniformBlockIndex(i,e.name),s.set(e,n))},uniformBlockBinding:function(e,i){const s=l.get(i).get(e);o.get(i)!==s&&(t.uniformBlockBinding(i,s,e.__bindingPointIndex),o.set(i,s))},texStorage2D:function(){try{t.texStorage2D.apply(t,arguments)}catch(t){}},texStorage3D:function(){try{t.texStorage3D.apply(t,arguments)}catch(t){}},texSubImage2D:function(){try{t.texSubImage2D.apply(t,arguments)}catch(t){}},texSubImage3D:function(){try{t.texSubImage3D.apply(t,arguments)}catch(t){}},compressedTexSubImage2D:function(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(t){}},compressedTexSubImage3D:function(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(t){}},scissor:function(e){!1===F.equals(e)&&(t.scissor(e.x,e.y,e.z,e.w),F.copy(e))},viewport:function(e){!1===U.equals(e)&&(t.viewport(e.x,e.y,e.z,e.w),U.copy(e))},reset:function(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),!0===s&&(t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),h={},D=null,I={},c={},d=new WeakMap,u=[],p=null,f=!1,m=null,_=null,g=null,v=null,y=null,S=null,x=null,T=!1,E=null,b=null,w=null,A=null,C=null,F.set(0,0,t.canvas.width,t.canvas.height),U.set(0,0,t.canvas.width,t.canvas.height),n.reset(),r.reset(),a.reset()}}}function iz(t,e,i,s,n,r,a){const o=n.isWebGL2,l=(n.maxTextures,n.maxCubemapSize),h=n.maxTextureSize,c=n.maxSamples,d=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,u="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),p=new WeakMap;let f;const m=new WeakMap;let _=!1;try{_="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function g(t,e){return _?new OffscreenCanvas(t,e):HI("canvas")}function v(t,e,i,s){let n=1;if((t.width>s||t.height>s)&&(n=s/Math.max(t.width,t.height)),n<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const s=e?NI:Math.floor,r=s(n*t.width),a=s(n*t.height);void 0===f&&(f=g(r,a));const o=i?g(r,a):f;o.width=r,o.height=a;return o.getContext("2d").drawImage(t,0,0,r,a),o}return t}return t}function y(t){return OI(t.width)&&OI(t.height)}function S(t,e){return t.generateMipmaps&&e&&t.minFilter!==UD&&t.minFilter!==kD}function x(e){t.generateMipmap(e)}function T(i,s,n,r,a=!1){if(!1===o)return s;if(null!==i&&void 0!==t[i])return t[i];let l=s;if(s===t.RED&&(n===t.FLOAT&&(l=t.R32F),n===t.HALF_FLOAT&&(l=t.R16F),n===t.UNSIGNED_BYTE&&(l=t.R8)),s===t.RED_INTEGER&&(n===t.UNSIGNED_BYTE&&(l=t.R8UI),n===t.UNSIGNED_SHORT&&(l=t.R16UI),n===t.UNSIGNED_INT&&(l=t.R32UI),n===t.BYTE&&(l=t.R8I),n===t.SHORT&&(l=t.R16I),n===t.INT&&(l=t.R32I)),s===t.RG&&(n===t.FLOAT&&(l=t.RG32F),n===t.HALF_FLOAT&&(l=t.RG16F),n===t.UNSIGNED_BYTE&&(l=t.RG8)),s===t.RGBA){const e=a?cI:KI.getTransfer(r);n===t.FLOAT&&(l=t.RGBA32F),n===t.HALF_FLOAT&&(l=t.RGBA16F),n===t.UNSIGNED_BYTE&&(l=e===dI?t.SRGB8_ALPHA8:t.RGBA8),n===t.UNSIGNED_SHORT_4_4_4_4&&(l=t.RGBA4),n===t.UNSIGNED_SHORT_5_5_5_1&&(l=t.RGB5_A1)}return l!==t.R16F&&l!==t.R32F&&l!==t.RG16F&&l!==t.RG32F&&l!==t.RGBA16F&&l!==t.RGBA32F||e.get("EXT_color_buffer_float"),l}function E(t,e,i){return!0===S(t,i)||t.isFramebufferTexture&&t.minFilter!==UD&&t.minFilter!==kD?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function b(e){return e===UD||1004===e||e===zD?t.NEAREST:t.LINEAR}function w(t){const e=t.target;e.removeEventListener("dispose",w),function(t){const e=s.get(t);if(void 0===e.__webglInit)return;const i=t.source,n=m.get(i);if(n){const s=n[e.__cacheKey];s.usedTimes--,0===s.usedTimes&&C(t),0===Object.keys(n).length&&m.delete(i)}s.remove(t)}(e),e.isVideoTexture&&p.delete(e)}function A(e){const i=e.target;i.removeEventListener("dispose",A),function(e){const i=e.texture,n=s.get(e),r=s.get(i);void 0!==r.__webglTexture&&(t.deleteTexture(r.__webglTexture),a.memory.textures--);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i<n.__webglFramebuffer[e].length;i++)t.deleteFramebuffer(n.__webglFramebuffer[e][i]);else t.deleteFramebuffer(n.__webglFramebuffer[e]);n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer[e])}else{if(Array.isArray(n.__webglFramebuffer))for(let e=0;e<n.__webglFramebuffer.length;e++)t.deleteFramebuffer(n.__webglFramebuffer[e]);else t.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&t.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let e=0;e<n.__webglColorRenderbuffer.length;e++)n.__webglColorRenderbuffer[e]&&t.deleteRenderbuffer(n.__webglColorRenderbuffer[e]);n.__webglDepthRenderbuffer&&t.deleteRenderbuffer(n.__webglDepthRenderbuffer)}if(e.isWebGLMultipleRenderTargets)for(let e=0,n=i.length;e<n;e++){const n=s.get(i[e]);n.__webglTexture&&(t.deleteTexture(n.__webglTexture),a.memory.textures--),s.remove(i[e])}s.remove(i),s.remove(e)}(i)}function C(e){const i=s.get(e);t.deleteTexture(i.__webglTexture);const n=e.source;delete m.get(n)[i.__cacheKey],a.memory.textures--}let M=0;function P(e,n){const r=s.get(e);if(e.isVideoTexture&&function(t){const e=a.render.frame;p.get(t)!==e&&(p.set(t,e),t.update())}(e),!1===e.isRenderTargetTexture&&e.version>0&&r.__version!==e.version){const t=e.image;if(null===t);else if(!1!==t.complete)return void N(r,e,n)}i.bindTexture(t.TEXTURE_2D,r.__webglTexture,t.TEXTURE0+n)}const R={[OD]:t.REPEAT,[ND]:t.CLAMP_TO_EDGE,[FD]:t.MIRRORED_REPEAT},L={[UD]:t.NEAREST,[BD]:t.NEAREST_MIPMAP_NEAREST,[zD]:t.NEAREST_MIPMAP_LINEAR,[kD]:t.LINEAR,[VD]:t.LINEAR_MIPMAP_NEAREST,[HD]:t.LINEAR_MIPMAP_LINEAR},D={[mI]:t.NEVER,[TI]:t.ALWAYS,[_I]:t.LESS,[vI]:t.LEQUAL,[gI]:t.EQUAL,[xI]:t.GEQUAL,[yI]:t.GREATER,[SI]:t.NOTEQUAL};function I(i,r,a){if(a?(t.texParameteri(i,t.TEXTURE_WRAP_S,R[r.wrapS]),t.texParameteri(i,t.TEXTURE_WRAP_T,R[r.wrapT]),i!==t.TEXTURE_3D&&i!==t.TEXTURE_2D_ARRAY||t.texParameteri(i,t.TEXTURE_WRAP_R,R[r.wrapR]),t.texParameteri(i,t.TEXTURE_MAG_FILTER,L[r.magFilter]),t.texParameteri(i,t.TEXTURE_MIN_FILTER,L[r.minFilter])):(t.texParameteri(i,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(i,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i!==t.TEXTURE_3D&&i!==t.TEXTURE_2D_ARRAY||t.texParameteri(i,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),r.wrapS!==ND||r.wrapT,t.texParameteri(i,t.TEXTURE_MAG_FILTER,b(r.magFilter)),t.texParameteri(i,t.TEXTURE_MIN_FILTER,b(r.minFilter)),r.minFilter!==UD&&r.minFilter),r.compareFunction&&(t.texParameteri(i,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(i,t.TEXTURE_COMPARE_FUNC,D[r.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){const a=e.get("EXT_texture_filter_anisotropic");if(r.magFilter===UD)return;if(r.minFilter!==zD&&r.minFilter!==HD)return;if(r.type===qD&&!1===e.has("OES_texture_float_linear"))return;if(!1===o&&r.type===jD&&!1===e.has("OES_texture_half_float_linear"))return;(r.anisotropy>1||s.get(r).__currentAnisotropy)&&(t.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r.anisotropy,n.getMaxAnisotropy())),s.get(r).__currentAnisotropy=r.anisotropy)}}function O(e,i){let s=!1;void 0===e.__webglInit&&(e.__webglInit=!0,i.addEventListener("dispose",w));const n=i.source;let r=m.get(n);void 0===r&&(r={},m.set(n,r));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(i);if(o!==e.__cacheKey){void 0===r[o]&&(r[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,s=!0),r[o].usedTimes++;const n=r[e.__cacheKey];void 0!==n&&(r[e.__cacheKey].usedTimes--,0===n.usedTimes&&C(i)),e.__cacheKey=o,e.__webglTexture=r[o].texture}return s}function N(e,n,a){let l=t.TEXTURE_2D;(n.isDataArrayTexture||n.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),n.isData3DTexture&&(l=t.TEXTURE_3D);const c=O(e,n),d=n.source;i.bindTexture(l,e.__webglTexture,t.TEXTURE0+a);const u=s.get(d);if(d.version!==u.__version||!0===c){i.activeTexture(t.TEXTURE0+a);const e=KI.getPrimaries(KI.workingColorSpace),s=n.colorSpace===rI?null:KI.getPrimaries(n.colorSpace),p=n.colorSpace===rI||e===s?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,n.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,n.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,p);const f=function(t){return!o&&(t.wrapS!==ND||t.wrapT!==ND||t.minFilter!==UD&&t.minFilter!==kD)}(n)&&!1===y(n.image);let m=v(n.image,f,!1,h);m=V(n,m);const _=y(m)||o,g=r.convert(n.format,n.colorSpace);let b,w=r.convert(n.type),A=T(n.internalFormat,g,w,n.colorSpace,n.isVideoTexture);I(l,n,_);const C=n.mipmaps,M=o&&!0!==n.isVideoTexture,P=void 0===u.__version||!0===c,R=E(n,m,_);if(n.isDepthTexture)A=t.DEPTH_COMPONENT,o?A=n.type===qD?t.DEPTH_COMPONENT32F:n.type===YD?t.DEPTH_COMPONENT24:n.type===$D?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT16:n.type,n.format===ZD&&A===t.DEPTH_COMPONENT&&n.type!==WD&&n.type!==YD&&(n.type=YD,w=r.convert(n.type)),n.format===QD&&A===t.DEPTH_COMPONENT&&(A=t.DEPTH_STENCIL,n.type!==$D&&(n.type=$D,w=r.convert(n.type))),P&&(M?i.texStorage2D(t.TEXTURE_2D,1,A,m.width,m.height):i.texImage2D(t.TEXTURE_2D,0,A,m.width,m.height,0,g,w,null));else if(n.isDataTexture)if(C.length>0&&_){M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,w,b.data):i.texImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,g,w,b.data);n.generateMipmaps=!1}else M?(P&&i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height),i.texSubImage2D(t.TEXTURE_2D,0,0,0,m.width,m.height,g,w,m.data)):i.texImage2D(t.TEXTURE_2D,0,A,m.width,m.height,0,g,w,m.data);else if(n.isCompressedTexture)if(n.isCompressedArrayTexture){M&&P&&i.texStorage3D(t.TEXTURE_2D_ARRAY,R,A,C[0].width,C[0].height,m.depth);for(let e=0,s=C.length;e<s;e++)b=C[e],n.format!==KD?null!==g&&(M?i.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,b.width,b.height,m.depth,g,b.data,0,0):i.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,A,b.width,b.height,m.depth,0,b.data,0,0)):M?i.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,b.width,b.height,m.depth,g,w,b.data):i.texImage3D(t.TEXTURE_2D_ARRAY,e,A,b.width,b.height,m.depth,0,g,w,b.data)}else{M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],n.format!==KD?null!==g&&(M?i.compressedTexSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,b.data):i.compressedTexImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,b.data)):M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,w,b.data):i.texImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,g,w,b.data)}else if(n.isDataArrayTexture)M?(P&&i.texStorage3D(t.TEXTURE_2D_ARRAY,R,A,m.width,m.height,m.depth),i.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,m.width,m.height,m.depth,g,w,m.data)):i.texImage3D(t.TEXTURE_2D_ARRAY,0,A,m.width,m.height,m.depth,0,g,w,m.data);else if(n.isData3DTexture)M?(P&&i.texStorage3D(t.TEXTURE_3D,R,A,m.width,m.height,m.depth),i.texSubImage3D(t.TEXTURE_3D,0,0,0,0,m.width,m.height,m.depth,g,w,m.data)):i.texImage3D(t.TEXTURE_3D,0,A,m.width,m.height,m.depth,0,g,w,m.data);else if(n.isFramebufferTexture){if(P)if(M)i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height);else{let e=m.width,s=m.height;for(let n=0;n<R;n++)i.texImage2D(t.TEXTURE_2D,n,A,e,s,0,g,w,null),e>>=1,s>>=1}}else if(C.length>0&&_){M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,g,w,b):i.texImage2D(t.TEXTURE_2D,e,A,g,w,b);n.generateMipmaps=!1}else M?(P&&i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height),i.texSubImage2D(t.TEXTURE_2D,0,0,0,g,w,m)):i.texImage2D(t.TEXTURE_2D,0,A,g,w,m);S(n,_)&&x(l),u.__version=d.version,n.onUpdate&&n.onUpdate(n)}e.__version=n.version}function F(e,n,a,o,l,h){const c=r.convert(a.format,a.colorSpace),u=r.convert(a.type),p=T(a.internalFormat,c,u,a.colorSpace);if(!s.get(n).__hasExternalTextures){const e=Math.max(1,n.width>>h),s=Math.max(1,n.height>>h);l===t.TEXTURE_3D||l===t.TEXTURE_2D_ARRAY?i.texImage3D(l,h,p,e,s,n.depth,0,c,u,null):i.texImage2D(l,h,p,e,s,0,c,u,null)}i.bindFramebuffer(t.FRAMEBUFFER,e),k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,l,s.get(a).__webglTexture,0,z(n)):(l===t.TEXTURE_2D||l>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,o,l,s.get(a).__webglTexture,h),i.bindFramebuffer(t.FRAMEBUFFER,null)}function U(e,i,s){if(t.bindRenderbuffer(t.RENDERBUFFER,e),i.depthBuffer&&!i.stencilBuffer){let n=!0===o?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(s||k(i)){const e=i.depthTexture;e&&e.isDepthTexture&&(e.type===qD?n=t.DEPTH_COMPONENT32F:e.type===YD&&(n=t.DEPTH_COMPONENT24));const s=z(i);k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,s,n,i.width,i.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,s,n,i.width,i.height)}else t.renderbufferStorage(t.RENDERBUFFER,n,i.width,i.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e)}else if(i.depthBuffer&&i.stencilBuffer){const n=z(i);s&&!1===k(i)?t.renderbufferStorageMultisample(t.RENDERBUFFER,n,t.DEPTH24_STENCIL8,i.width,i.height):k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,n,t.DEPTH24_STENCIL8,i.width,i.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,i.width,i.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e)}else{const e=!0===i.isWebGLMultipleRenderTargets?i.texture:[i.texture];for(let n=0;n<e.length;n++){const a=e[n],o=r.convert(a.format,a.colorSpace),l=r.convert(a.type),h=T(a.internalFormat,o,l,a.colorSpace),c=z(i);s&&!1===k(i)?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,h,i.width,i.height):k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,h,i.width,i.height):t.renderbufferStorage(t.RENDERBUFFER,h,i.width,i.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function B(e){const n=s.get(e),r=!0===e.isWebGLCubeRenderTarget;if(e.depthTexture&&!n.__autoAllocateDepthBuffer){if(r)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,n){if(n&&n.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(i.bindFramebuffer(t.FRAMEBUFFER,e),!n.depthTexture||!n.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");s.get(n.depthTexture).__webglTexture&&n.depthTexture.image.width===n.width&&n.depthTexture.image.height===n.height||(n.depthTexture.image.width=n.width,n.depthTexture.image.height=n.height,n.depthTexture.needsUpdate=!0),P(n.depthTexture,0);const r=s.get(n.depthTexture).__webglTexture,a=z(n);if(n.depthTexture.format===ZD)k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,r,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,r,0);else{if(n.depthTexture.format!==QD)throw new Error("Unknown depthTexture format");k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,r,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,r,0)}}(n.__webglFramebuffer,e)}else if(r){n.__webglDepthbuffer=[];for(let s=0;s<6;s++)i.bindFramebuffer(t.FRAMEBUFFER,n.__webglFramebuffer[s]),n.__webglDepthbuffer[s]=t.createRenderbuffer(),U(n.__webglDepthbuffer[s],e,!1)}else i.bindFramebuffer(t.FRAMEBUFFER,n.__webglFramebuffer),n.__webglDepthbuffer=t.createRenderbuffer(),U(n.__webglDepthbuffer,e,!1);i.bindFramebuffer(t.FRAMEBUFFER,null)}function z(t){return Math.min(c,t.samples)}function k(t){const i=s.get(t);return o&&t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function V(t,i){const s=t.colorSpace,n=t.format;t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||t.format===bI||s!==oI&&s!==rI&&KI.getTransfer(s)===dI&&!1===o&&(!0===e.has("EXT_sRGB")&&n===KD?(t.format=bI,t.minFilter=kD,t.generateMipmaps=!1):i=tO.sRGBToLinear(i)),i}this.allocateTextureUnit=function(){const t=M;return M+=1,t},this.resetTextureUnits=function(){M=0},this.setTexture2D=P,this.setTexture2DArray=function(e,n){const r=s.get(e);e.version>0&&r.__version!==e.version?N(r,e,n):i.bindTexture(t.TEXTURE_2D_ARRAY,r.__webglTexture,t.TEXTURE0+n)},this.setTexture3D=function(e,n){const r=s.get(e);e.version>0&&r.__version!==e.version?N(r,e,n):i.bindTexture(t.TEXTURE_3D,r.__webglTexture,t.TEXTURE0+n)},this.setTextureCube=function(e,n){const a=s.get(e);e.version>0&&a.__version!==e.version?function(e,n,a){if(6!==n.image.length)return;const h=O(e,n),c=n.source;i.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+a);const d=s.get(c);if(c.version!==d.__version||!0===h){i.activeTexture(t.TEXTURE0+a);const e=KI.getPrimaries(KI.workingColorSpace),s=n.colorSpace===rI?null:KI.getPrimaries(n.colorSpace),u=n.colorSpace===rI||e===s?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,n.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,n.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const p=n.isCompressedTexture||n.image[0].isCompressedTexture,f=n.image[0]&&n.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=p||f?f?n.image[t].image:n.image[t]:v(n.image[t],!1,!0,l),m[t]=V(n,m[t]);const _=m[0],g=y(_)||o,b=r.convert(n.format,n.colorSpace),w=r.convert(n.type),A=T(n.internalFormat,b,w,n.colorSpace),C=o&&!0!==n.isVideoTexture,M=void 0===d.__version||!0===h;let P,R=E(n,_,g);if(I(t.TEXTURE_CUBE_MAP,n,g),p){C&&M&&i.texStorage2D(t.TEXTURE_CUBE_MAP,R,A,_.width,_.height);for(let e=0;e<6;e++){P=m[e].mipmaps;for(let s=0;s<P.length;s++){const r=P[s];n.format!==KD?null!==b&&(C?i.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,0,0,r.width,r.height,b,r.data):i.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,A,r.width,r.height,0,r.data)):C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,0,0,r.width,r.height,b,w,r.data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,A,r.width,r.height,0,b,w,r.data)}}}else{P=n.mipmaps,C&&M&&(P.length>0&&R++,i.texStorage2D(t.TEXTURE_CUBE_MAP,R,A,m[0].width,m[0].height));for(let e=0;e<6;e++)if(f){C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,b,w,m[e].data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,A,m[e].width,m[e].height,0,b,w,m[e].data);for(let s=0;s<P.length;s++){const n=P[s].image[e].image;C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,0,0,n.width,n.height,b,w,n.data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,A,n.width,n.height,0,b,w,n.data)}}else{C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,b,w,m[e]):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,A,b,w,m[e]);for(let s=0;s<P.length;s++){const n=P[s];C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,0,0,b,w,n.image[e]):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,A,b,w,n.image[e])}}}S(n,g)&&x(t.TEXTURE_CUBE_MAP),d.__version=c.version,n.onUpdate&&n.onUpdate(n)}e.__version=n.version}(a,e,n):i.bindTexture(t.TEXTURE_CUBE_MAP,a.__webglTexture,t.TEXTURE0+n)},this.rebindTextures=function(e,i,n){const r=s.get(e);void 0!==i&&F(r.__webglFramebuffer,e,e.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),void 0!==n&&B(e)},this.setupRenderTarget=function(e){const l=e.texture,h=s.get(e),c=s.get(l);e.addEventListener("dispose",A),!0!==e.isWebGLMultipleRenderTargets&&(void 0===c.__webglTexture&&(c.__webglTexture=t.createTexture()),c.__version=l.version,a.memory.textures++);const d=!0===e.isWebGLCubeRenderTarget,u=!0===e.isWebGLMultipleRenderTargets,p=y(e)||o;if(d){h.__webglFramebuffer=[];for(let e=0;e<6;e++)if(o&&l.mipmaps&&l.mipmaps.length>0){h.__webglFramebuffer[e]=[];for(let i=0;i<l.mipmaps.length;i++)h.__webglFramebuffer[e][i]=t.createFramebuffer()}else h.__webglFramebuffer[e]=t.createFramebuffer()}else{if(o&&l.mipmaps&&l.mipmaps.length>0){h.__webglFramebuffer=[];for(let e=0;e<l.mipmaps.length;e++)h.__webglFramebuffer[e]=t.createFramebuffer()}else h.__webglFramebuffer=t.createFramebuffer();if(u&&n.drawBuffers){const i=e.texture;for(let e=0,n=i.length;e<n;e++){const n=s.get(i[e]);void 0===n.__webglTexture&&(n.__webglTexture=t.createTexture(),a.memory.textures++)}}if(o&&e.samples>0&&!1===k(e)){const s=u?l:[l];h.__webglMultisampledFramebuffer=t.createFramebuffer(),h.__webglColorRenderbuffer=[],i.bindFramebuffer(t.FRAMEBUFFER,h.__webglMultisampledFramebuffer);for(let i=0;i<s.length;i++){const n=s[i];h.__webglColorRenderbuffer[i]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,h.__webglColorRenderbuffer[i]);const a=r.convert(n.format,n.colorSpace),o=r.convert(n.type),l=T(n.internalFormat,a,o,n.colorSpace,!0===e.isXRRenderTarget),c=z(e);t.renderbufferStorageMultisample(t.RENDERBUFFER,c,l,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+i,t.RENDERBUFFER,h.__webglColorRenderbuffer[i])}t.bindRenderbuffer(t.RENDERBUFFER,null),e.depthBuffer&&(h.__webglDepthRenderbuffer=t.createRenderbuffer(),U(h.__webglDepthRenderbuffer,e,!0)),i.bindFramebuffer(t.FRAMEBUFFER,null)}}if(d){i.bindTexture(t.TEXTURE_CUBE_MAP,c.__webglTexture),I(t.TEXTURE_CUBE_MAP,l,p);for(let i=0;i<6;i++)if(o&&l.mipmaps&&l.mipmaps.length>0)for(let s=0;s<l.mipmaps.length;s++)F(h.__webglFramebuffer[i][s],e,l,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+i,s);else F(h.__webglFramebuffer[i],e,l,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+i,0);S(l,p)&&x(t.TEXTURE_CUBE_MAP),i.unbindTexture()}else if(u){const n=e.texture;for(let r=0,a=n.length;r<a;r++){const a=n[r],o=s.get(a);i.bindTexture(t.TEXTURE_2D,o.__webglTexture),I(t.TEXTURE_2D,a,p),F(h.__webglFramebuffer,e,a,t.COLOR_ATTACHMENT0+r,t.TEXTURE_2D,0),S(a,p)&&x(t.TEXTURE_2D)}i.unbindTexture()}else{let s=t.TEXTURE_2D;if((e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&o&&(s=e.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),i.bindTexture(s,c.__webglTexture),I(s,l,p),o&&l.mipmaps&&l.mipmaps.length>0)for(let i=0;i<l.mipmaps.length;i++)F(h.__webglFramebuffer[i],e,l,t.COLOR_ATTACHMENT0,s,i);else F(h.__webglFramebuffer,e,l,t.COLOR_ATTACHMENT0,s,0);S(l,p)&&x(s),i.unbindTexture()}e.depthBuffer&&B(e)},this.updateRenderTargetMipmap=function(e){const n=y(e)||o,r=!0===e.isWebGLMultipleRenderTargets?e.texture:[e.texture];for(let a=0,o=r.length;a<o;a++){const o=r[a];if(S(o,n)){const n=e.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,r=s.get(o).__webglTexture;i.bindTexture(n,r),x(n),i.unbindTexture()}}},this.updateMultisampleRenderTarget=function(e){if(o&&e.samples>0&&!1===k(e)){const n=e.isWebGLMultipleRenderTargets?e.texture:[e.texture],r=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const l=[],h=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=s.get(e),d=!0===e.isWebGLMultipleRenderTargets;if(d)for(let e=0;e<n.length;e++)i.bindFramebuffer(t.FRAMEBUFFER,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),i.bindFramebuffer(t.FRAMEBUFFER,c.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);i.bindFramebuffer(t.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let i=0;i<n.length;i++){l.push(t.COLOR_ATTACHMENT0+i),e.depthBuffer&&l.push(h);const p=void 0!==c.__ignoreDepthValues&&c.__ignoreDepthValues;if(!1===p&&(e.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),e.stencilBuffer&&(o|=t.STENCIL_BUFFER_BIT)),d&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c.__webglColorRenderbuffer[i]),!0===p&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[h]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[h])),d){const e=s.get(n[i]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}t.blitFramebuffer(0,0,r,a,0,0,r,a,o,t.NEAREST),u&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,l)}if(i.bindFramebuffer(t.READ_FRAMEBUFFER,null),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),d)for(let e=0;e<n.length;e++){i.bindFramebuffer(t.FRAMEBUFFER,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,c.__webglColorRenderbuffer[e]);const r=s.get(n[e]).__webglTexture;i.bindFramebuffer(t.FRAMEBUFFER,c.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,r,0)}i.bindFramebuffer(t.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}},this.setupDepthRenderbuffer=B,this.setupFrameBufferTexture=F,this.useMultisampledRTT=k}function sz(t,e,i){const s=i.isWebGL2;return{convert:function(i,n=""){let r;const a=KI.getTransfer(n);if(i===GD)return t.UNSIGNED_BYTE;if(1017===i)return t.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return t.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return t.BYTE;if(1011===i)return t.SHORT;if(i===WD)return t.UNSIGNED_SHORT;if(i===XD)return t.INT;if(i===YD)return t.UNSIGNED_INT;if(i===qD)return t.FLOAT;if(i===jD)return s?t.HALF_FLOAT:(r=e.get("OES_texture_half_float"),null!==r?r.HALF_FLOAT_OES:null);if(1021===i)return t.ALPHA;if(i===KD)return t.RGBA;if(1024===i)return t.LUMINANCE;if(1025===i)return t.LUMINANCE_ALPHA;if(i===ZD)return t.DEPTH_COMPONENT;if(i===QD)return t.DEPTH_STENCIL;if(i===bI)return r=e.get("EXT_sRGB"),null!==r?r.SRGB_ALPHA_EXT:null;if(1028===i)return t.RED;if(1029===i)return t.RED_INTEGER;if(1030===i)return t.RG;if(1031===i)return t.RG_INTEGER;if(1033===i)return t.RGBA_INTEGER;if(i===JD||i===tI||i===eI||i===iI)if(a===dI){if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(i===JD)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===tI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===eI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===iI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=e.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(i===JD)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===tI)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===eI)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===iI)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){if(r=e.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===i)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i)return r=e.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(37492===i||37496===i){if(r=e.get("WEBGL_compressed_texture_etc"),null===r)return null;if(37492===i)return a===dI?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(37496===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){if(r=e.get("WEBGL_compressed_texture_astc"),null===r)return null;if(37808===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===sI||36494===i||36495===i){if(r=e.get("EXT_texture_compression_bptc"),null===r)return null;if(i===sI)return a===dI?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(36494===i)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(36495===i)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(36283===i||36284===i||36285===i||36286===i){if(r=e.get("EXT_texture_compression_rgtc"),null===r)return null;if(i===sI)return r.COMPRESSED_RED_RGTC1_EXT;if(36284===i)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(36285===i)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(36286===i)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===$D?s?t.UNSIGNED_INT_24_8:(r=e.get("WEBGL_depth_texture"),null!==r?r.UNSIGNED_INT_24_8_WEBGL:null):void 0!==t[i]?t[i]:null}}}class nz extends xF{constructor(t=[]){super(),this.isArrayCamera=!0,this.cameras=t}}class rz extends pN{constructor(){super(),this.isGroup=!0,this.type="Group"}}const az={type:"move"};class oz{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new rz,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new rz,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new uO,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new uO),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new rz,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new uO,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new uO),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,i){let s=null,n=null,r=null;const a=this._targetRay,o=this._grip,l=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState){if(l&&t.hand){r=!0;for(const s of t.hand.values()){const t=e.getJointPose(s,i),n=this._getHandJoint(l,s);null!==t&&(n.matrix.fromArray(t.transform.matrix),n.matrix.decompose(n.position,n.rotation,n.scale),n.matrixWorldNeedsUpdate=!0,n.jointRadius=t.radius),n.visible=null!==t}const s=l.joints["index-finger-tip"],n=l.joints["thumb-tip"],a=s.position.distanceTo(n.position),o=.02,h=.005;l.inputState.pinching&&a>o+h?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-h&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(n=e.getPose(t.gripSpace,i),null!==n&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(s=e.getPose(t.targetRaySpace,i),null===s&&null!==n&&(s=n),null!==s&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(az)))}return null!==a&&(a.visible=null!==s),null!==o&&(o.visible=null!==n),null!==l&&(l.visible=null!==r),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const i=new rz;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}class lz extends rO{constructor(t,e,i,s,n,r,a,o,l,h){if((h=void 0!==h?h:ZD)!==ZD&&h!==QD)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===i&&h===ZD&&(i=YD),void 0===i&&h===QD&&(i=$D),super(null,s,n,r,a,o,h,i,l),this.isDepthTexture=!0,this.image={width:t,height:e},this.magFilter=void 0!==a?a:UD,this.minFilter=void 0!==o?o:UD,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return null!==this.compareFunction&&(e.compareFunction=this.compareFunction),e}}class hz extends CI{constructor(t,e){super();const i=this;let s=null,n=1,r=null,a="local-floor",o=1,l=null,h=null,c=null,d=null,u=null,p=null;const f=e.getContextAttributes();let m=null,_=null;const g=[],v=[],y=new xF;y.layers.enable(1),y.viewport=new aO;const S=new xF;S.layers.enable(2),S.viewport=new aO;const x=[y,S],T=new nz;T.layers.enable(1),T.layers.enable(2);let E=null,b=null;function w(t){const e=v.indexOf(t.inputSource);if(-1===e)return;const i=g[e];void 0!==i&&(i.update(t.inputSource,t.frame,l||r),i.dispatchEvent({type:t.type,data:t.inputSource}))}function A(){s.removeEventListener("select",w),s.removeEventListener("selectstart",w),s.removeEventListener("selectend",w),s.removeEventListener("squeeze",w),s.removeEventListener("squeezestart",w),s.removeEventListener("squeezeend",w),s.removeEventListener("end",A),s.removeEventListener("inputsourceschange",C);for(let t=0;t<g.length;t++){const e=v[t];null!==e&&(v[t]=null,g[t].disconnect(e))}E=null,b=null,t.setRenderTarget(m),u=null,d=null,c=null,s=null,_=null,D.stop(),i.isPresenting=!1,i.dispatchEvent({type:"sessionend"})}function C(t){for(let e=0;e<t.removed.length;e++){const i=t.removed[e],s=v.indexOf(i);s>=0&&(v[s]=null,g[s].disconnect(i))}for(let e=0;e<t.added.length;e++){const i=t.added[e];let s=v.indexOf(i);if(-1===s){for(let t=0;t<g.length;t++){if(t>=v.length){v.push(i),s=t;break}if(null===v[t]){v[t]=i,s=t;break}}if(-1===s)break}const n=g[s];n&&n.connect(i)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getGripSpace()},this.getHand=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){n=t,i.isPresenting},this.setReferenceSpaceType=function(t){a=t,i.isPresenting},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==d?d:u},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(h){if(s=h,null!==s){if(m=t.getRenderTarget(),s.addEventListener("select",w),s.addEventListener("selectstart",w),s.addEventListener("selectend",w),s.addEventListener("squeeze",w),s.addEventListener("squeezestart",w),s.addEventListener("squeezeend",w),s.addEventListener("end",A),s.addEventListener("inputsourceschange",C),!0!==f.xrCompatible&&await e.makeXRCompatible(),void 0===s.renderState.layers||!1===t.capabilities.isWebGL2){const i={antialias:void 0!==s.renderState.layers||f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:n};u=new XRWebGLLayer(s,e,i),s.updateRenderState({baseLayer:u}),_=new lO(u.framebufferWidth,u.framebufferHeight,{format:KD,type:GD,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let i=null,r=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,i=f.stencil?QD:ZD,r=f.stencil?$D:YD);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:n};c=new XRWebGLBinding(s,e),d=c.createProjectionLayer(o),s.updateRenderState({layers:[d]}),_=new lO(d.textureWidth,d.textureHeight,{format:KD,type:GD,depthTexture:new lz(d.textureWidth,d.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,i),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0});t.properties.get(_).__ignoreDepthValues=d.ignoreDepthValues}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,r=await s.requestReferenceSpace(a),D.setContext(s),D.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==s)return s.environmentBlendMode};const M=new uO,P=new uO;function R(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===s)return;T.near=S.near=y.near=t.near,T.far=S.far=y.far=t.far,E===T.near&&b===T.far||(s.updateRenderState({depthNear:T.near,depthFar:T.far}),E=T.near,b=T.far);const e=t.parent,i=T.cameras;R(T,e);for(let t=0;t<i.length;t++)R(i[t],e);2===i.length?function(t,e,i){M.setFromMatrixPosition(e.matrixWorld),P.setFromMatrixPosition(i.matrixWorld);const s=M.distanceTo(P),n=e.projectionMatrix.elements,r=i.projectionMatrix.elements,a=n[14]/(n[10]-1),o=n[14]/(n[10]+1),l=(n[9]+1)/n[5],h=(n[9]-1)/n[5],c=(n[8]-1)/n[0],d=(r[8]+1)/r[0],u=a*c,p=a*d,f=s/(-c+d),m=f*-c;e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(m),t.translateZ(f),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.copy(t.matrixWorld).invert();const _=a+f,g=o+f,v=u-m,y=p+(s-m),S=l*o/g*_,x=h*o/g*_;t.projectionMatrix.makePerspective(v,y,S,x,_,g),t.projectionMatrixInverse.copy(t.projectionMatrix).invert()}(T,y,S):T.projectionMatrix.copy(y.projectionMatrix),function(t,e,i){null===i?t.matrix.copy(e.matrixWorld):(t.matrix.copy(i.matrixWorld),t.matrix.invert(),t.matrix.multiply(e.matrixWorld));t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(!0),t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse),t.isPerspectiveCamera&&(t.fov=2*RI*Math.atan(1/t.projectionMatrix.elements[5]),t.zoom=1)}(t,T,e)},this.getCamera=function(){return T},this.getFoveation=function(){if(null!==d||null!==u)return o},this.setFoveation=function(t){o=t,null!==d&&(d.fixedFoveation=t),null!==u&&void 0!==u.fixedFoveation&&(u.fixedFoveation=t)};let L=null;const D=new IF;D.setAnimationLoop(function(e,s){if(h=s.getViewerPose(l||r),p=s,null!==h){const e=h.views;null!==u&&(t.setRenderTargetFramebuffer(_,u.framebuffer),t.setRenderTarget(_));let i=!1;e.length!==T.cameras.length&&(T.cameras.length=0,i=!0);for(let s=0;s<e.length;s++){const n=e[s];let r=null;if(null!==u)r=u.getViewport(n);else{const e=c.getViewSubImage(d,n);r=e.viewport,0===s&&(t.setRenderTargetTextures(_,e.colorTexture,d.ignoreDepthValues?void 0:e.depthStencilTexture),t.setRenderTarget(_))}let a=x[s];void 0===a&&(a=new xF,a.layers.enable(s),a.viewport=new aO,x[s]=a),a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(n.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(r.x,r.y,r.width,r.height),0===s&&(T.matrix.copy(a.matrix),T.matrix.decompose(T.position,T.quaternion,T.scale)),!0===i&&T.cameras.push(a)}}for(let t=0;t<g.length;t++){const e=v[t],i=g[t];null!==e&&void 0!==i&&i.update(e,s,l||r)}L&&L(e,s),s.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:s}),p=null}),this.setAnimationLoop=function(t){L=t},this.dispose=function(){}}}function cz(t,e){function i(t,e){!0===t.matrixAutoUpdate&&t.updateMatrix(),e.value.copy(t.matrix)}function s(s,n){s.opacity.value=n.opacity,n.color&&s.diffuse.value.copy(n.color),n.emissive&&s.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(s.map.value=n.map,i(n.map,s.mapTransform)),n.alphaMap&&(s.alphaMap.value=n.alphaMap,i(n.alphaMap,s.alphaMapTransform)),n.bumpMap&&(s.bumpMap.value=n.bumpMap,i(n.bumpMap,s.bumpMapTransform),s.bumpScale.value=n.bumpScale,1===n.side&&(s.bumpScale.value*=-1)),n.normalMap&&(s.normalMap.value=n.normalMap,i(n.normalMap,s.normalMapTransform),s.normalScale.value.copy(n.normalScale),1===n.side&&s.normalScale.value.negate()),n.displacementMap&&(s.displacementMap.value=n.displacementMap,i(n.displacementMap,s.displacementMapTransform),s.displacementScale.value=n.displacementScale,s.displacementBias.value=n.displacementBias),n.emissiveMap&&(s.emissiveMap.value=n.emissiveMap,i(n.emissiveMap,s.emissiveMapTransform)),n.specularMap&&(s.specularMap.value=n.specularMap,i(n.specularMap,s.specularMapTransform)),n.alphaTest>0&&(s.alphaTest.value=n.alphaTest);const r=e.get(n).envMap;if(r&&(s.envMap.value=r,s.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,s.reflectivity.value=n.reflectivity,s.ior.value=n.ior,s.refractionRatio.value=n.refractionRatio),n.lightMap){s.lightMap.value=n.lightMap;const e=!0===t._useLegacyLights?Math.PI:1;s.lightMapIntensity.value=n.lightMapIntensity*e,i(n.lightMap,s.lightMapTransform)}n.aoMap&&(s.aoMap.value=n.aoMap,s.aoMapIntensity.value=n.aoMapIntensity,i(n.aoMap,s.aoMapTransform))}return{refreshFogUniforms:function(e,i){i.color.getRGB(e.fogColor.value,gF(t)),i.isFog?(e.fogNear.value=i.near,e.fogFar.value=i.far):i.isFogExp2&&(e.fogDensity.value=i.density)},refreshMaterialUniforms:function(t,n,r,a,o){n.isMeshBasicMaterial||n.isMeshLambertMaterial?s(t,n):n.isMeshToonMaterial?(s(t,n),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,n)):n.isMeshPhongMaterial?(s(t,n),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,n)):n.isMeshStandardMaterial?(s(t,n),function(t,s){t.metalness.value=s.metalness,s.metalnessMap&&(t.metalnessMap.value=s.metalnessMap,i(s.metalnessMap,t.metalnessMapTransform));t.roughness.value=s.roughness,s.roughnessMap&&(t.roughnessMap.value=s.roughnessMap,i(s.roughnessMap,t.roughnessMapTransform));const n=e.get(s).envMap;n&&(t.envMapIntensity.value=s.envMapIntensity)}(t,n),n.isMeshPhysicalMaterial&&function(t,e,s){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,i(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,i(e.sheenRoughnessMap,t.sheenRoughnessMapTransform)));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,i(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,i(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,i(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),1===e.side&&t.clearcoatNormalScale.value.negate()));e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,i(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,i(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform)));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=s.texture,t.transmissionSamplerSize.value.set(s.width,s.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,i(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,i(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,i(e.anisotropyMap,t.anisotropyMapTransform)));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,i(e.specularColorMap,t.specularColorMapTransform));e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,i(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,n,o)):n.isMeshMatcapMaterial?(s(t,n),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,n)):n.isMeshDepthMaterial?s(t,n):n.isMeshDistanceMaterial?(s(t,n),function(t,i){const s=e.get(i).light;t.referencePosition.value.setFromMatrixPosition(s.matrixWorld),t.nearDistance.value=s.shadow.camera.near,t.farDistance.value=s.shadow.camera.far}(t,n)):n.isMeshNormalMaterial?s(t,n):n.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,i(e.map,t.mapTransform))}(t,n),n.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,n)):n.isPointsMaterial?function(t,e,s,n){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*s,t.scale.value=.5*n,e.map&&(t.map.value=e.map,i(e.map,t.uvTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,i(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,n,r,a):n.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,i(e.map,t.mapTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,i(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,n):n.isShadowMaterial?(t.color.value.copy(n.color),t.opacity.value=n.opacity):n.isShaderMaterial&&(n.uniformsNeedUpdate=!1)}}}function dz(t,e,i,s){let n={},r={},a=[];const o=i.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(t,e,i){const s=t.value;if(void 0===i[e]){if("number"==typeof s)i[e]=s;else{const t=Array.isArray(s)?s:[s],n=[];for(let e=0;e<t.length;e++)n.push(t[e].clone());i[e]=n}return!0}if("number"==typeof s){if(i[e]!==s)return i[e]=s,!0}else{const t=Array.isArray(i[e])?i[e]:[i[e]],n=Array.isArray(s)?s:[s];for(let e=0;e<t.length;e++){const i=t[e];if(!1===i.equals(n[e]))return i.copy(n[e]),!0}}return!1}function h(t){const e={boundary:0,storage:0};return"number"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture,e}function c(e){const i=e.target;i.removeEventListener("dispose",c);const s=a.indexOf(i.__bindingPointIndex);a.splice(s,1),t.deleteBuffer(n[i.id]),delete n[i.id],delete r[i.id]}return{bind:function(t,e){const i=e.program;s.uniformBlockBinding(t,i)},update:function(i,d){let u=n[i.id];void 0===u&&(!function(t){const e=t.uniforms;let i=0;const s=16;let n=0;for(let t=0,r=e.length;t<r;t++){const r=e[t],a={boundary:0,storage:0},o=Array.isArray(r.value)?r.value:[r.value];for(let t=0,e=o.length;t<e;t++){const e=h(o[t]);a.boundary+=e.boundary,a.storage+=e.storage}if(r.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),r.__offset=i,t>0){n=i%s;0!==n&&s-n-a.boundary<0&&(i+=s-n,r.__offset=i)}i+=a.storage}n=i%s,n>0&&(i+=s-n);t.__size=i,t.__cache={}}(i),u=function(e){const i=function(){for(let t=0;t<o;t++)if(-1===a.indexOf(t))return a.push(t),t;return 0}();e.__bindingPointIndex=i;const s=t.createBuffer(),n=e.__size,r=e.usage;return t.bindBuffer(t.UNIFORM_BUFFER,s),t.bufferData(t.UNIFORM_BUFFER,n,r),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,i,s),s}(i),n[i.id]=u,i.addEventListener("dispose",c));const p=d.program;s.updateUBOMapping(i,p);const f=e.render.frame;r[i.id]!==f&&(!function(e){const i=n[e.id],s=e.uniforms,r=e.__cache;t.bindBuffer(t.UNIFORM_BUFFER,i);for(let e=0,i=s.length;e<i;e++){const i=s[e];if(!0===l(i,e,r)){const e=i.__offset,s=Array.isArray(i.value)?i.value:[i.value];let n=0;for(let r=0;r<s.length;r++){const a=s[r],o=h(a);"number"==typeof a?(i.__data[0]=a,t.bufferSubData(t.UNIFORM_BUFFER,e+n,i.__data)):a.isMatrix3?(i.__data[0]=a.elements[0],i.__data[1]=a.elements[1],i.__data[2]=a.elements[2],i.__data[3]=a.elements[0],i.__data[4]=a.elements[3],i.__data[5]=a.elements[4],i.__data[6]=a.elements[5],i.__data[7]=a.elements[0],i.__data[8]=a.elements[6],i.__data[9]=a.elements[7],i.__data[10]=a.elements[8],i.__data[11]=a.elements[0]):(a.toArray(i.__data,n),n+=o.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,e,i.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}(i),r[i.id]=f)},dispose:function(){for(const e in n)t.deleteBuffer(n[e]);a=[],n={},r={}}}}class uz{constructor(t={}){const{canvas:e=GI(),context:i=null,depth:s=!0,stencil:n=!0,alpha:r=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:c=!1}=t;let d;this.isWebGLRenderer=!0,d=null!==i?i.getContextAttributes().alpha:r;const u=new Uint32Array(4),p=new Int32Array(4);let f=null,m=null;const _=[],g=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=aI,this._useLegacyLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const v=this;let y=!1,S=0,x=0,T=null,E=-1,b=null;const w=new aO,A=new aO;let C=null;const M=new DN(0);let P=0,R=e.width,L=e.height,D=1,I=null,O=null;const N=new aO(0,0,R,L),F=new aO(0,0,R,L);let U=!1;const B=new DF;let z=!1,k=!1,V=null;const H=new HO,G=new BI,W=new uO,X={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Y(){return null===T?D:1}let q,j,$,K,Z,Q,J,tt,et,it,st,nt,rt,at,ot,lt,ht,ct,dt,ut,pt,ft,mt,_t,gt=i;function vt(t,i){for(let s=0;s<t.length;s++){const n=t[s],r=e.getContext(n,i);if(null!==r)return r}return null}try{const t={alpha:!0,depth:s,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:c};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${pD}`),e.addEventListener("webglcontextlost",xt,!1),e.addEventListener("webglcontextrestored",Tt,!1),e.addEventListener("webglcontextcreationerror",Et,!1),null===gt){const e=["webgl2","webgl","experimental-webgl"];if(!0===v.isWebGL1Renderer&&e.shift(),gt=vt(e,t),null===gt)throw vt(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}"undefined"!=typeof WebGLRenderingContext&&WebGLRenderingContext,void 0===gt.getShaderPrecisionFormat&&(gt.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(t){throw t}function yt(){q=new lU(gt),j=new GF(gt,q,t),q.init(j),ft=new sz(gt,q,j),$=new ez(gt,q,j),K=new dU(gt),Z=new VB,Q=new iz(gt,q,$,Z,j,ft,K),J=new XF(v),tt=new oU(v),et=new OF(gt,j),mt=new VF(gt,q,et,j),it=new hU(gt,et,K,mt),st=new mU(gt,it,et,K),dt=new fU(gt,j,Q),lt=new WF(Z),nt=new kB(v,J,tt,q,j,mt,lt),rt=new cz(v,Z),at=new XB,ot=new ZB(q,j),ct=new kF(v,J,tt,$,st,d,o),ht=new tz(v,st,j),_t=new dz(gt,K,j,$),ut=new HF(gt,q,K,j),pt=new cU(gt,q,K,j),K.programs=nt.programs,v.capabilities=j,v.extensions=q,v.properties=Z,v.renderLists=at,v.shadowMap=ht,v.state=$,v.info=K}yt();const St=new hz(v,gt);function xt(t){t.preventDefault(),y=!0}function Tt(){y=!1;const t=K.autoReset,e=ht.enabled,i=ht.autoUpdate,s=ht.needsUpdate,n=ht.type;yt(),K.autoReset=t,ht.enabled=e,ht.autoUpdate=i,ht.needsUpdate=s,ht.type=n}function Et(t){}function bt(t){const e=t.target;e.removeEventListener("dispose",bt),function(t){(function(t){const e=Z.get(t).programs;void 0!==e&&(e.forEach(function(t){nt.releaseProgram(t)}),t.isShaderMaterial&&nt.releaseShaderCache(t))})(t),Z.remove(t)}(e)}this.xr=St,this.getContext=function(){return gt},this.getContextAttributes=function(){return gt.getContextAttributes()},this.forceContextLoss=function(){const t=q.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=q.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return D},this.setPixelRatio=function(t){void 0!==t&&(D=t,this.setSize(R,L,!1))},this.getSize=function(t){return t.set(R,L)},this.setSize=function(t,i,s=!0){St.isPresenting||(R=t,L=i,e.width=Math.floor(t*D),e.height=Math.floor(i*D),!0===s&&(e.style.width=t+"px",e.style.height=i+"px"),this.setViewport(0,0,t,i))},this.getDrawingBufferSize=function(t){return t.set(R*D,L*D).floor()},this.setDrawingBufferSize=function(t,i,s){R=t,L=i,D=s,e.width=Math.floor(t*s),e.height=Math.floor(i*s),this.setViewport(0,0,t,i)},this.getCurrentViewport=function(t){return t.copy(w)},this.getViewport=function(t){return t.copy(N)},this.setViewport=function(t,e,i,s){t.isVector4?N.set(t.x,t.y,t.z,t.w):N.set(t,e,i,s),$.viewport(w.copy(N).multiplyScalar(D).floor())},this.getScissor=function(t){return t.copy(F)},this.setScissor=function(t,e,i,s){t.isVector4?F.set(t.x,t.y,t.z,t.w):F.set(t,e,i,s),$.scissor(A.copy(F).multiplyScalar(D).floor())},this.getScissorTest=function(){return U},this.setScissorTest=function(t){$.setScissorTest(U=t)},this.setOpaqueSort=function(t){I=t},this.setTransparentSort=function(t){O=t},this.getClearColor=function(t){return t.copy(ct.getClearColor())},this.setClearColor=function(){ct.setClearColor.apply(ct,arguments)},this.getClearAlpha=function(){return ct.getClearAlpha()},this.setClearAlpha=function(){ct.setClearAlpha.apply(ct,arguments)},this.clear=function(t=!0,e=!0,i=!0){let s=0;if(t){let t=!1;if(null!==T){const e=T.texture.format;t=1033===e||1031===e||1029===e}if(t){const t=T.texture.type,e=t===GD||t===YD||t===WD||t===$D||1017===t||1018===t,i=ct.getClearColor(),s=ct.getClearAlpha(),n=i.r,r=i.g,a=i.b;e?(u[0]=n,u[1]=r,u[2]=a,u[3]=s,gt.clearBufferuiv(gt.COLOR,0,u)):(p[0]=n,p[1]=r,p[2]=a,p[3]=s,gt.clearBufferiv(gt.COLOR,0,p))}else s|=gt.COLOR_BUFFER_BIT}e&&(s|=gt.DEPTH_BUFFER_BIT),i&&(s|=gt.STENCIL_BUFFER_BIT),gt.clear(s)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",xt,!1),e.removeEventListener("webglcontextrestored",Tt,!1),e.removeEventListener("webglcontextcreationerror",Et,!1),at.dispose(),ot.dispose(),Z.dispose(),J.dispose(),tt.dispose(),st.dispose(),mt.dispose(),_t.dispose(),nt.dispose(),St.dispose(),St.removeEventListener("sessionstart",At),St.removeEventListener("sessionend",Ct),V&&(V.dispose(),V=null),Mt.stop()},this.renderBufferDirect=function(t,e,i,s,n,r){null===e&&(e=X);const a=n.isMesh&&n.matrixWorld.determinant()<0,o=function(t,e,i,s,n){!0!==e.isScene&&(e=X);Q.resetTextureUnits();const r=e.fog,a=s.isMeshStandardMaterial?e.environment:null,o=null===T?v.outputColorSpace:!0===T.isXRRenderTarget?T.texture.colorSpace:oI,l=(s.isMeshStandardMaterial?tt:J).get(s.envMap||a),h=!0===s.vertexColors&&!!i.attributes.color&&4===i.attributes.color.itemSize,c=!!i.attributes.tangent&&(!!s.normalMap||s.anisotropy>0),d=!!i.morphAttributes.position,u=!!i.morphAttributes.normal,p=!!i.morphAttributes.color;let f=0;s.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(f=v.toneMapping));const _=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,g=void 0!==_?_.length:0,y=Z.get(s),S=m.state.lights;if(!0===z&&(!0===k||t!==b)){const e=t===b&&s.id===E;lt.setState(s,t,e)}let x=!1;s.version===y.__version?y.needsLights&&y.lightsStateVersion!==S.state.version||y.outputColorSpace!==o||n.isInstancedMesh&&!1===y.instancing?x=!0:n.isInstancedMesh||!0!==y.instancing?n.isSkinnedMesh&&!1===y.skinning?x=!0:n.isSkinnedMesh||!0!==y.skinning?n.isInstancedMesh&&!0===y.instancingColor&&null===n.instanceColor||n.isInstancedMesh&&!1===y.instancingColor&&null!==n.instanceColor||y.envMap!==l||!0===s.fog&&y.fog!==r?x=!0:void 0===y.numClippingPlanes||y.numClippingPlanes===lt.numPlanes&&y.numIntersection===lt.numIntersection?(y.vertexAlphas!==h||y.vertexTangents!==c||y.morphTargets!==d||y.morphNormals!==u||y.morphColors!==p||y.toneMapping!==f||!0===j.isWebGL2&&y.morphTargetsCount!==g)&&(x=!0):x=!0:x=!0:x=!0:(x=!0,y.__version=s.version);let w=y.currentProgram;!0===x&&(w=It(s,e,n));let A=!1,C=!1,M=!1;const P=w.getUniforms(),R=y.uniforms;$.useProgram(w.program)&&(A=!0,C=!0,M=!0);s.id!==E&&(E=s.id,C=!0);if(A||b!==t){P.setValue(gt,"projectionMatrix",t.projectionMatrix),P.setValue(gt,"viewMatrix",t.matrixWorldInverse);const e=P.map.cameraPosition;void 0!==e&&e.setValue(gt,W.setFromMatrixPosition(t.matrixWorld)),j.logarithmicDepthBuffer&&P.setValue(gt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(s.isMeshPhongMaterial||s.isMeshToonMaterial||s.isMeshLambertMaterial||s.isMeshBasicMaterial||s.isMeshStandardMaterial||s.isShaderMaterial)&&P.setValue(gt,"isOrthographic",!0===t.isOrthographicCamera),b!==t&&(b=t,C=!0,M=!0)}if(n.isSkinnedMesh){P.setOptional(gt,n,"bindMatrix"),P.setOptional(gt,n,"bindMatrixInverse");const t=n.skeleton;t&&j.floatVertexTextures&&(null===t.boneTexture&&t.computeBoneTexture(),P.setValue(gt,"boneTexture",t.boneTexture,Q),P.setValue(gt,"boneTextureSize",t.boneTextureSize))}const I=i.morphAttributes;(void 0!==I.position||void 0!==I.normal||void 0!==I.color&&!0===j.isWebGL2)&&dt.update(n,i,w);(C||y.receiveShadow!==n.receiveShadow)&&(y.receiveShadow=n.receiveShadow,P.setValue(gt,"receiveShadow",n.receiveShadow));s.isMeshGouraudMaterial&&null!==s.envMap&&(R.envMap.value=l,R.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);C&&(P.setValue(gt,"toneMappingExposure",v.toneMappingExposure),y.needsLights&&(N=M,(O=R).ambientLightColor.needsUpdate=N,O.lightProbe.needsUpdate=N,O.directionalLights.needsUpdate=N,O.directionalLightShadows.needsUpdate=N,O.pointLights.needsUpdate=N,O.pointLightShadows.needsUpdate=N,O.spotLights.needsUpdate=N,O.spotLightShadows.needsUpdate=N,O.rectAreaLights.needsUpdate=N,O.hemisphereLights.needsUpdate=N),r&&!0===s.fog&&rt.refreshFogUniforms(R,r),rt.refreshMaterialUniforms(R,s,D,L,V),yB.upload(gt,y.uniformsList,R,Q));var O,N;s.isShaderMaterial&&!0===s.uniformsNeedUpdate&&(yB.upload(gt,y.uniformsList,R,Q),s.uniformsNeedUpdate=!1);s.isSpriteMaterial&&P.setValue(gt,"center",n.center);if(P.setValue(gt,"modelViewMatrix",n.modelViewMatrix),P.setValue(gt,"normalMatrix",n.normalMatrix),P.setValue(gt,"modelMatrix",n.matrixWorld),s.isShaderMaterial||s.isRawShaderMaterial){const t=s.uniformsGroups;for(let e=0,i=t.length;e<i;e++)if(j.isWebGL2){const i=t[e];_t.update(i,w),_t.bind(i,w)}}return w}(t,e,i,s,n);$.setMaterial(s,a);let l=i.index,h=1;if(!0===s.wireframe){if(l=it.getWireframeAttribute(i),void 0===l)return;h=2}const c=i.drawRange,d=i.attributes.position;let u=c.start*h,p=(c.start+c.count)*h;null!==r&&(u=Math.max(u,r.start*h),p=Math.min(p,(r.start+r.count)*h)),null!==l?(u=Math.max(u,0),p=Math.min(p,l.count)):null!=d&&(u=Math.max(u,0),p=Math.min(p,d.count));const f=p-u;if(f<0||f===1/0)return;let _;mt.setup(n,s,o,i,l);let g=ut;if(null!==l&&(_=et.get(l),g=pt,g.setIndex(_)),n.isMesh)!0===s.wireframe?($.setLineWidth(s.wireframeLinewidth*Y()),g.setMode(gt.LINES)):g.setMode(gt.TRIANGLES);else if(n.isLine){let t=s.linewidth;void 0===t&&(t=1),$.setLineWidth(t*Y()),n.isLineSegments?g.setMode(gt.LINES):n.isLineLoop?g.setMode(gt.LINE_LOOP):g.setMode(gt.LINE_STRIP)}else n.isPoints?g.setMode(gt.POINTS):n.isSprite&&g.setMode(gt.TRIANGLES);if(n.isInstancedMesh)g.renderInstances(u,f,n.count);else if(i.isInstancedBufferGeometry){const t=void 0!==i._maxInstanceCount?i._maxInstanceCount:1/0,e=Math.min(i.instanceCount,t);g.renderInstances(u,f,e)}else g.render(u,f)},this.compile=function(t,e){function i(t,e,i){!0===t.transparent&&2===t.side&&!1===t.forceSinglePass?(t.side=1,t.needsUpdate=!0,It(t,e,i),t.side=0,t.needsUpdate=!0,It(t,e,i),t.side=2):It(t,e,i)}m=ot.get(t),m.init(),g.push(m),t.traverseVisible(function(t){t.isLight&&t.layers.test(e.layers)&&(m.pushLight(t),t.castShadow&&m.pushShadow(t))}),m.setupLights(v._useLegacyLights),t.traverse(function(e){const s=e.material;if(s)if(Array.isArray(s))for(let n=0;n<s.length;n++){i(s[n],t,e)}else i(s,t,e)}),g.pop(),m=null};let wt=null;function At(){Mt.stop()}function Ct(){Mt.start()}const Mt=new IF;function Pt(t,e,i,s){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)i=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)m.pushLight(t),t.castShadow&&m.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||B.intersectsSprite(t)){s&&W.setFromMatrixPosition(t.matrixWorld).applyMatrix4(H);const e=st.update(t),n=t.material;n.visible&&f.push(t,e,n,i,W.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||B.intersectsObject(t))){const e=st.update(t),n=t.material;if(s&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),W.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),W.copy(e.boundingSphere.center)),W.applyMatrix4(t.matrixWorld).applyMatrix4(H)),Array.isArray(n)){const s=e.groups;for(let r=0,a=s.length;r<a;r++){const a=s[r],o=n[a.materialIndex];o&&o.visible&&f.push(t,e,o,i,W.z,a)}}else n.visible&&f.push(t,e,n,i,W.z,null)}const n=t.children;for(let t=0,r=n.length;t<r;t++)Pt(n[t],e,i,s)}function Rt(t,e,i,s){const n=t.opaque,r=t.transmissive,a=t.transparent;m.setupLightsView(i),!0===z&<.setGlobalState(v.clippingPlanes,i),r.length>0&&function(t,e,i,s){const n=j.isWebGL2;null===V&&(V=new lO(1,1,{generateMipmaps:!0,type:q.has("EXT_color_buffer_half_float")?jD:GD,minFilter:HD,samples:n?4:0}));v.getDrawingBufferSize(G),n?V.setSize(G.x,G.y):V.setSize(NI(G.x),NI(G.y));const r=v.getRenderTarget();v.setRenderTarget(V),v.getClearColor(M),P=v.getClearAlpha(),P<1&&v.setClearColor(16777215,.5);v.clear();const a=v.toneMapping;v.toneMapping=0,Lt(t,i,s),Q.updateMultisampleRenderTarget(V),Q.updateRenderTargetMipmap(V);let o=!1;for(let t=0,n=e.length;t<n;t++){const n=e[t],r=n.object,a=n.geometry,l=n.material,h=n.group;if(2===l.side&&r.layers.test(s.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,Dt(r,i,s,a,l,h),l.side=t,l.needsUpdate=!0,o=!0}}!0===o&&(Q.updateMultisampleRenderTarget(V),Q.updateRenderTargetMipmap(V));v.setRenderTarget(r),v.setClearColor(M,P),v.toneMapping=a}(n,r,e,i),s&&$.viewport(w.copy(s)),n.length>0&&Lt(n,e,i),r.length>0&&Lt(r,e,i),a.length>0&&Lt(a,e,i),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function Lt(t,e,i){const s=!0===e.isScene?e.overrideMaterial:null;for(let n=0,r=t.length;n<r;n++){const r=t[n],a=r.object,o=r.geometry,l=null===s?r.material:s,h=r.group;a.layers.test(i.layers)&&Dt(a,e,i,o,l,h)}}function Dt(t,e,i,s,n,r){t.onBeforeRender(v,e,i,s,n,r),t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix),n.onBeforeRender(v,e,i,s,t,r),!0===n.transparent&&2===n.side&&!1===n.forceSinglePass?(n.side=1,n.needsUpdate=!0,v.renderBufferDirect(i,e,s,n,t,r),n.side=0,n.needsUpdate=!0,v.renderBufferDirect(i,e,s,n,t,r),n.side=2):v.renderBufferDirect(i,e,s,n,t,r),t.onAfterRender(v,e,i,s,n,r)}function It(t,e,i){!0!==e.isScene&&(e=X);const s=Z.get(t),n=m.state.lights,r=m.state.shadowsArray,a=n.state.version,o=nt.getParameters(t,n.state,r,e,i),l=nt.getProgramCacheKey(o);let h=s.programs;s.environment=t.isMeshStandardMaterial?e.environment:null,s.fog=e.fog,s.envMap=(t.isMeshStandardMaterial?tt:J).get(t.envMap||s.environment),void 0===h&&(t.addEventListener("dispose",bt),h=new Map,s.programs=h);let c=h.get(l);if(void 0!==c){if(s.currentProgram===c&&s.lightsStateVersion===a)return Ot(t,o),c}else o.uniforms=nt.getUniforms(t),t.onBuild(i,o,v),t.onBeforeCompile(o,v),c=nt.acquireProgram(o,l),h.set(l,c),s.uniforms=o.uniforms;const d=s.uniforms;(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(d.clippingPlanes=lt.uniform),Ot(t,o),s.needsLights=function(t){return t.isMeshLambertMaterial||t.isMeshToonMaterial||t.isMeshPhongMaterial||t.isMeshStandardMaterial||t.isShadowMaterial||t.isShaderMaterial&&!0===t.lights}(t),s.lightsStateVersion=a,s.needsLights&&(d.ambientLightColor.value=n.state.ambient,d.lightProbe.value=n.state.probe,d.directionalLights.value=n.state.directional,d.directionalLightShadows.value=n.state.directionalShadow,d.spotLights.value=n.state.spot,d.spotLightShadows.value=n.state.spotShadow,d.rectAreaLights.value=n.state.rectArea,d.ltc_1.value=n.state.rectAreaLTC1,d.ltc_2.value=n.state.rectAreaLTC2,d.pointLights.value=n.state.point,d.pointLightShadows.value=n.state.pointShadow,d.hemisphereLights.value=n.state.hemi,d.directionalShadowMap.value=n.state.directionalShadowMap,d.directionalShadowMatrix.value=n.state.directionalShadowMatrix,d.spotShadowMap.value=n.state.spotShadowMap,d.spotLightMatrix.value=n.state.spotLightMatrix,d.spotLightMap.value=n.state.spotLightMap,d.pointShadowMap.value=n.state.pointShadowMap,d.pointShadowMatrix.value=n.state.pointShadowMatrix);const u=c.getUniforms(),p=yB.seqWithValue(u.seq,d);return s.currentProgram=c,s.uniformsList=p,c}function Ot(t,e){const i=Z.get(t);i.outputColorSpace=e.outputColorSpace,i.instancing=e.instancing,i.instancingColor=e.instancingColor,i.skinning=e.skinning,i.morphTargets=e.morphTargets,i.morphNormals=e.morphNormals,i.morphColors=e.morphColors,i.morphTargetsCount=e.morphTargetsCount,i.numClippingPlanes=e.numClippingPlanes,i.numIntersection=e.numClipIntersection,i.vertexAlphas=e.vertexAlphas,i.vertexTangents=e.vertexTangents,i.toneMapping=e.toneMapping}Mt.setAnimationLoop(function(t){wt&&wt(t)}),"undefined"!=typeof self&&Mt.setContext(self),this.setAnimationLoop=function(t){wt=t,St.setAnimationLoop(t),null===t?Mt.stop():Mt.start()},St.addEventListener("sessionstart",At),St.addEventListener("sessionend",Ct),this.render=function(t,e){if(void 0!==e&&!0!==e.isCamera)return;if(!0===y)return;!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===St.enabled&&!0===St.isPresenting&&(!0===St.cameraAutoUpdate&&St.updateCamera(e),e=St.getCamera()),!0===t.isScene&&t.onBeforeRender(v,t,e,T),m=ot.get(t,g.length),m.init(),g.push(m),H.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),B.setFromProjectionMatrix(H),k=this.localClippingEnabled,z=lt.init(this.clippingPlanes,k),f=at.get(t,_.length),f.init(),_.push(f),Pt(t,e,0,v.sortObjects),f.finish(),!0===v.sortObjects&&f.sort(I,O),this.info.render.frame++,!0===z&<.beginShadows();const i=m.state.shadowsArray;if(ht.render(i,t,e),!0===z&<.endShadows(),!0===this.info.autoReset&&this.info.reset(),ct.render(f,t),m.setupLights(v._useLegacyLights),e.isArrayCamera){const i=e.cameras;for(let e=0,s=i.length;e<s;e++){const s=i[e];Rt(f,t,s,s.viewport)}}else Rt(f,t,e);null!==T&&(Q.updateMultisampleRenderTarget(T),Q.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(v,t,e),mt.resetDefaultState(),E=-1,b=null,g.pop(),m=g.length>0?g[g.length-1]:null,_.pop(),f=_.length>0?_[_.length-1]:null},this.getActiveCubeFace=function(){return S},this.getActiveMipmapLevel=function(){return x},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,i){Z.get(t.texture).__webglTexture=e,Z.get(t.depthTexture).__webglTexture=i;const s=Z.get(t);s.__hasExternalTextures=!0,s.__hasExternalTextures&&(s.__autoAllocateDepthBuffer=void 0===i,s.__autoAllocateDepthBuffer||!0===q.has("WEBGL_multisampled_render_to_texture")&&(s.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(t,e){const i=Z.get(t);i.__webglFramebuffer=e,i.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,i=0){T=t,S=e,x=i;let s=!0,n=null,r=!1,a=!1;if(t){const o=Z.get(t);void 0!==o.__useDefaultFramebuffer?($.bindFramebuffer(gt.FRAMEBUFFER,null),s=!1):void 0===o.__webglFramebuffer?Q.setupRenderTarget(t):o.__hasExternalTextures&&Q.rebindTextures(t,Z.get(t.texture).__webglTexture,Z.get(t.depthTexture).__webglTexture);const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const h=Z.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(n=Array.isArray(h[e])?h[e][i]:h[e],r=!0):n=j.isWebGL2&&t.samples>0&&!1===Q.useMultisampledRTT(t)?Z.get(t).__webglMultisampledFramebuffer:Array.isArray(h)?h[i]:h,w.copy(t.viewport),A.copy(t.scissor),C=t.scissorTest}else w.copy(N).multiplyScalar(D).floor(),A.copy(F).multiplyScalar(D).floor(),C=U;if($.bindFramebuffer(gt.FRAMEBUFFER,n)&&j.drawBuffers&&s&&$.drawBuffers(t,n),$.viewport(w),$.scissor(A),$.setScissorTest(C),r){const s=Z.get(t.texture);gt.framebufferTexture2D(gt.FRAMEBUFFER,gt.COLOR_ATTACHMENT0,gt.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.__webglTexture,i)}else if(a){const s=Z.get(t.texture),n=e||0;gt.framebufferTextureLayer(gt.FRAMEBUFFER,gt.COLOR_ATTACHMENT0,s.__webglTexture,i||0,n)}E=-1},this.readRenderTargetPixels=function(t,e,i,s,n,r,a){if(!t||!t.isWebGLRenderTarget)return;let o=Z.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){$.bindFramebuffer(gt.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(o!==KD&&ft.convert(o)!==gt.getParameter(gt.IMPLEMENTATION_COLOR_READ_FORMAT))return;const h=l===jD&&(q.has("EXT_color_buffer_half_float")||j.isWebGL2&&q.has("EXT_color_buffer_float"));if(!(l===GD||ft.convert(l)===gt.getParameter(gt.IMPLEMENTATION_COLOR_READ_TYPE)||l===qD&&(j.isWebGL2||q.has("OES_texture_float")||q.has("WEBGL_color_buffer_float"))||h))return;e>=0&&e<=t.width-s&&i>=0&&i<=t.height-n&>.readPixels(e,i,s,n,ft.convert(o),ft.convert(l),r)}finally{const t=null!==T?Z.get(T).__webglFramebuffer:null;$.bindFramebuffer(gt.FRAMEBUFFER,t)}}},this.copyFramebufferToTexture=function(t,e,i=0){const s=Math.pow(2,-i),n=Math.floor(e.image.width*s),r=Math.floor(e.image.height*s);Q.setTexture2D(e,0),gt.copyTexSubImage2D(gt.TEXTURE_2D,i,0,0,t.x,t.y,n,r),$.unbindTexture()},this.copyTextureToTexture=function(t,e,i,s=0){const n=e.image.width,r=e.image.height,a=ft.convert(i.format),o=ft.convert(i.type);Q.setTexture2D(i,0),gt.pixelStorei(gt.UNPACK_FLIP_Y_WEBGL,i.flipY),gt.pixelStorei(gt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),gt.pixelStorei(gt.UNPACK_ALIGNMENT,i.unpackAlignment),e.isDataTexture?gt.texSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,n,r,a,o,e.image.data):e.isCompressedTexture?gt.compressedTexSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,e.mipmaps[0].width,e.mipmaps[0].height,a,e.mipmaps[0].data):gt.texSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,a,o,e.image),0===s&&i.generateMipmaps&>.generateMipmap(gt.TEXTURE_2D),$.unbindTexture()},this.copyTextureToTexture3D=function(t,e,i,s,n=0){if(v.isWebGL1Renderer)return;const r=t.max.x-t.min.x+1,a=t.max.y-t.min.y+1,o=t.max.z-t.min.z+1,l=ft.convert(s.format),h=ft.convert(s.type);let c;if(s.isData3DTexture)Q.setTexture3D(s,0),c=gt.TEXTURE_3D;else{if(!s.isDataArrayTexture)return;Q.setTexture2DArray(s,0),c=gt.TEXTURE_2D_ARRAY}gt.pixelStorei(gt.UNPACK_FLIP_Y_WEBGL,s.flipY),gt.pixelStorei(gt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,s.premultiplyAlpha),gt.pixelStorei(gt.UNPACK_ALIGNMENT,s.unpackAlignment);const d=gt.getParameter(gt.UNPACK_ROW_LENGTH),u=gt.getParameter(gt.UNPACK_IMAGE_HEIGHT),p=gt.getParameter(gt.UNPACK_SKIP_PIXELS),f=gt.getParameter(gt.UNPACK_SKIP_ROWS),m=gt.getParameter(gt.UNPACK_SKIP_IMAGES),_=i.isCompressedTexture?i.mipmaps[0]:i.image;gt.pixelStorei(gt.UNPACK_ROW_LENGTH,_.width),gt.pixelStorei(gt.UNPACK_IMAGE_HEIGHT,_.height),gt.pixelStorei(gt.UNPACK_SKIP_PIXELS,t.min.x),gt.pixelStorei(gt.UNPACK_SKIP_ROWS,t.min.y),gt.pixelStorei(gt.UNPACK_SKIP_IMAGES,t.min.z),i.isDataTexture||i.isData3DTexture?gt.texSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,h,_.data):i.isCompressedArrayTexture?gt.compressedTexSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,_.data):gt.texSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,h,_),gt.pixelStorei(gt.UNPACK_ROW_LENGTH,d),gt.pixelStorei(gt.UNPACK_IMAGE_HEIGHT,u),gt.pixelStorei(gt.UNPACK_SKIP_PIXELS,p),gt.pixelStorei(gt.UNPACK_SKIP_ROWS,f),gt.pixelStorei(gt.UNPACK_SKIP_IMAGES,m),0===n&&s.generateMipmaps&>.generateMipmap(c),$.unbindTexture()},this.initTexture=function(t){t.isCubeTexture?Q.setTextureCube(t,0):t.isData3DTexture?Q.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?Q.setTexture2DArray(t,0):Q.setTexture2D(t,0),$.unbindTexture()},this.resetState=function(){S=0,x=0,T=null,$.reset(),mt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return wI}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===lI?"display-p3":"srgb",e.unpackColorSpace=KI.workingColorSpace===hI?"display-p3":"srgb"}get physicallyCorrectLights(){return!this.useLegacyLights}set physicallyCorrectLights(t){this.useLegacyLights=!t}get outputEncoding(){return this.outputColorSpace===aI?nI:3e3}set outputEncoding(t){this.outputColorSpace=t===nI?aI:oI}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(t){this._useLegacyLights=t}}(class extends uz{}).prototype.isWebGL1Renderer=!0;let pz=class extends pN{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e}};class fz extends CN{constructor(t){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new DN(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 DN(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new BI(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class mz extends pN{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new DN(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}const _z=new HO,gz=new uO,vz=new uO;class yz{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new BI(512,512),this.map=null,this.mapPass=null,this.matrix=new HO,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new DF,this._frameExtents=new BI(1,1),this._viewportCount=1,this._viewports=[new aO(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,i=this.matrix;gz.setFromMatrixPosition(t.matrixWorld),e.position.copy(gz),vz.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(vz),e.updateMatrixWorld(),_z.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(_z),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(_z)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Sz extends yz{constructor(){super(new YF(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class xz extends mz{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(pN.DEFAULT_UP),this.updateMatrix(),this.target=new pN,this.shadow=new Sz}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class Tz extends mz{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:pD}})),"undefined"!=typeof window&&(window.__THREE__||(window.__THREE__=pD));class Ez{constructor(t){this.scene=null,this.camera=null,this.renderer=null,this.cube=null,this.directionalLight=null,this.ambientLight=null,this.canvas=null,this.initialized=!1,this.visible=!0,this.animationFrameId=null,this.needsRender=!1,this.resizeObserver=null}initialize(t){try{this.canvas=t,this.scene=new pz,this.scene.background=null;const e=t.clientWidth||t.width,i=e/(t.clientHeight||t.height)||1,s=4.5;this.camera=new YF(s*i/-2,s*i/2,s/2,s/-2,.1,1e3),this.camera.position.set(5,0,0),this.camera.lookAt(0,0,0),this.camera.updateProjectionMatrix(),this.renderer=new uz({canvas:t,alpha:!0,antialias:!0});const n=t.clientWidth||t.width,r=t.clientHeight||t.height;if(this.renderer.setSize(n,r,!1),this.renderer.setPixelRatio(window.devicePixelRatio||1),!this.renderer.getContext())throw new Error("Failed to create WebGL context");const a=new fF(1,1,1),o=new fz({color:11184810,metalness:.7,roughness:.3,emissive:1710623,emissiveIntensity:.1});this.cube=new uF(a,o),this.cube.position.set(0,0,0),this.scene.add(this.cube),this.directionalLight=new xz(16777215,2.2),this.directionalLight.position.set(2,3,2),this.scene.add(this.directionalLight);const l=new xz(16777215,.8);l.position.set(-1,.5,-1),this.scene.add(l);const h=new xz(16777215,1.2);h.position.set(-2,-1.5,2),this.scene.add(h);const c=new xz(16777215,1.2);c.position.set(2,-1.5,2),this.scene.add(c);const d=new xz(16777215,.4);d.position.set(0,-1,-2),this.scene.add(d),this.ambientLight=new Tz(13421789,.35),this.scene.add(this.ambientLight),this.setupResizeObserver(),this.requestRender(),this.initialized=!0}catch(t){throw this.initialized=!1,this.cleanup(),t}}setRotation(t,e){if(!this.initialized||!this.camera)return;if(!isFinite(t)||!isFinite(e))return;const i=t*(Math.PI/180),s=e*(Math.PI/180),n=5*Math.sin(s)*Math.cos(i),r=5*Math.sin(i),a=5*Math.cos(s)*Math.cos(i);this.camera.position.set(n,r,a),this.camera.lookAt(0,0,0),this.requestRender()}setVisible(t){this.visible=t,this.canvas&&(this.canvas.style.display=t?"block":"none",t&&this.initialized&&this.requestRender())}setupResizeObserver(){this.canvas&&(this.resizeObserver=new ResizeObserver(t=>{for(const e of t){const{width:t,height:i}=e.contentRect;this.onCanvasResize(t,i)}}),this.resizeObserver.observe(this.canvas))}onCanvasResize(t,e){if(!this.camera||!this.renderer)return;const i=t/e||1,s=4.5;this.camera.left=s*i/-2,this.camera.right=s*i/2,this.camera.top=2.25,this.camera.bottom=-2.25,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,e,!1),this.requestRender()}requestRender(){this.needsRender||(this.needsRender=!0,this.animationFrameId=requestAnimationFrame(()=>{this.render(),this.needsRender=!1,this.animationFrameId=null}))}render(){this.initialized&&this.visible&&this.scene&&this.camera&&this.renderer&&this.renderer.render(this.scene,this.camera)}cleanup(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.needsRender=!1,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.cube&&(this.cube.geometry&&this.cube.geometry.dispose(),this.cube.material&&(Array.isArray(this.cube.material)?this.cube.material.forEach(t=>t.dispose()):this.cube.material.dispose()),this.cube=null),this.scene&&(this.scene.clear(),this.scene=null),this.renderer&&(this.renderer.dispose(),this.renderer=null),this.camera=null,this.directionalLight=null,this.ambientLight=null,this.canvas=null}destroy(){this.cleanup(),this.initialized=!1}isInitialized(){return this.initialized}isVisible(){return this.visible}}class bz{constructor(t,e){this.cubeEntity=null,this.cubeMaterial=null,this.cubeCamera=null,this.directionalLight=null,this.ambientLight=null,this.cubeRoot=null,this.initialized=!1,this.visible=!0,this.MIN_CANVAS_SIZE=200,this.MIN_PARENT_DIV_SIZE=100,this.cubeLayer=null,this.separateCanvas=null,this.parentDiv=null,this.resizeObserver=null,this.useParentDiv=!1,this.onResizeCallback=null,this.threeJsRenderer=null,this.useThreeJs=!1,this.mainApp=t,this.app=t,this.config=e,this.useParentDiv=!!e.parentElementId}initialize(){if(!this.initialized)try{this.useParentDiv&&this.config.parentElementId?this.initializeInParentDiv():this.initializeInMainCanvas(),this.initialized=!0}catch(t){throw this.cleanup(),t}}initializeInMainCanvas(){this.setupCubeLayer(),this.cubeRoot=new z_("NavigationCubeRoot"),this.app.root.addChild(this.cubeRoot),this.cubeMaterial=this.createCubeMaterial(),this.cubeEntity=this.createCubeGeometry(),this.cubeCamera=this.setupCubeCamera(),this.setupCubeLighting(),this.updateViewport()}initializeInParentDiv(){const t=this.config.parentElementId;if(this.parentDiv=document.getElementById(t),!this.parentDiv)return this.useParentDiv=!1,void this.initializeInMainCanvas();const e=this.parentDiv.querySelector("#navigation-cube-canvas");e&&e.remove(),this.separateCanvas=document.createElement("canvas"),this.separateCanvas.id="navigation-cube-canvas",this.separateCanvas.style.width="100%",this.separateCanvas.style.height="100%",this.separateCanvas.style.display="block",this.separateCanvas.style.position="absolute",this.separateCanvas.style.top="0",this.separateCanvas.style.left="0",this.parentDiv.appendChild(this.separateCanvas);const i=this.parentDiv.getBoundingClientRect();this.separateCanvas.width=Math.floor(i.width),this.separateCanvas.height=Math.floor(i.height);try{this.threeJsRenderer=new Ez(this.config),this.threeJsRenderer.initialize(this.separateCanvas),this.useThreeJs=!0,this.useParentDiv=!0}catch(t){return this.useParentDiv=!1,this.useThreeJs=!1,this.app=this.mainApp,void this.initializeInMainCanvas()}}setupCubeLayer(){this.cubeLayer=new iu({name:"NavigationCubeLayer",opaqueSortMode:0,transparentSortMode:0});this.app.scene.layers.push(this.cubeLayer)}createCubeGeometry(){const t=new z_("NavigationCube");return t.addComponent("render",{type:"box",material:this.cubeMaterial,castShadows:!1,receiveShadows:!1,layers:[this.cubeLayer.id]}),t.setLocalPosition(0,0,0),this.cubeRoot.addChild(t),t}createCubeMaterial(){const t=new Xf;return t.diffuse=new H(.6,.6,.65),t.metalness=.5,t.gloss=.5,t.useMetalness=!0,t.emissive=new H(.1,.1,.12),t.emissiveIntensity=.15,t.update(),t}setupCubeCamera(){const t=new z_("NavigationCubeCamera"),e=this.useParentDiv,i=new H(0,0,0,e?1:0);return t.addComponent("camera",{projection:1,orthoHeight:1.5,clearColor:i,clearColorBuffer:e,clearDepthBuffer:!0,priority:100,farClip:100,nearClip:.1,layers:[this.cubeLayer.id]}),t.setLocalPosition(0,0,5),t.lookAt(0,0,0),this.cubeRoot.addChild(t),t}setupCubeLighting(){this.directionalLight=new z_("CubeDirectionalLight");const t={type:"directional",color:new H(1,1,1),intensity:1.5,castShadows:!1};this.cubeLayer&&(t.layers=[this.cubeLayer.id]),this.directionalLight.addComponent("light",t),this.directionalLight.setLocalEulerAngles(45,45,0),this.cubeCamera.addChild(this.directionalLight),this.ambientLight=new z_("CubeAmbientLight");const e={type:"directional",color:new H(.8,.8,.85),intensity:.7,castShadows:!1};this.cubeLayer&&(e.layers=[this.cubeLayer.id]),this.ambientLight.addComponent("light",e),this.ambientLight.setLocalEulerAngles(-45,-135,0),this.cubeCamera.addChild(this.ambientLight)}setRotation(t,e){if(this.initialized)if(this.useThreeJs&&this.threeJsRenderer)this.threeJsRenderer.setRotation(t,e);else if(this.cubeCamera&&"number"==typeof t&&"number"==typeof e)try{const i=5,s=t*(Math.PI/180),n=e*(Math.PI/180),r=i*Math.sin(n)*Math.cos(s),a=i*Math.sin(s),o=i*Math.cos(n)*Math.cos(s);this.cubeCamera.setLocalPosition(r,a,o),this.cubeCamera.lookAt(0,0,0)}catch(t){}}render(){this.initialized&&this.visible&&this.useThreeJs}setVisible(t){this.visible=t,this.useThreeJs&&this.threeJsRenderer?this.threeJsRenderer.setVisible(t):this.initialized&&this.cubeRoot&&(this.cubeRoot.enabled=t)}isVisible(){return this.visible}updateSize(t){if("number"!=typeof t||!isFinite(t))return;const e=Math.max(50,Math.min(500,t));this.config.cubeSize=e,this.initialized&&this.cubeCamera&&this.updateViewport()}shouldShowCube(){if(this.useParentDiv&&this.parentDiv){const t=this.parentDiv.clientWidth,e=this.parentDiv.clientHeight;return t>=this.MIN_PARENT_DIV_SIZE&&e>=this.MIN_PARENT_DIV_SIZE}const t=this.app.graphicsDevice.canvas;if(!t)return!1;const e=t.width,i=t.height;return e>=this.MIN_CANVAS_SIZE&&i>=this.MIN_CANVAS_SIZE}updateViewport(){if(!this.cubeCamera||!this.cubeCamera.camera)return;const t=this.app.graphicsDevice.canvas;if(!t)return;const e=t.width,i=t.height;if(e<=0||i<=0)return;if(!this.shouldShowCube())return void(this.cubeRoot&&(this.cubeRoot.enabled=!1));this.cubeRoot&&!this.cubeRoot.enabled&&this.visible&&(this.cubeRoot.enabled=!0);const s=this.config.cubeSize;let n=s/e,r=s/i,a=1-n-this.config.padding.x/e,o=1-r-this.config.padding.y/i;a=Math.max(0,Math.min(a,1-n)),o=Math.max(0,Math.min(o,1-r)),n=Math.max(0,Math.min(n,1-a)),r=Math.max(0,Math.min(r,1-o)),this.cubeCamera.camera.rect=new J(a,o,n,r)}onCanvasResize(){this.initialized&&(this.updateViewport(),this.onResizeCallback&&this.onResizeCallback())}setResizeCallback(t){this.onResizeCallback=t}cleanup(){if(this.threeJsRenderer&&(this.threeJsRenderer.destroy(),this.threeJsRenderer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.ambientLight&&(this.ambientLight.destroy(),this.ambientLight=null),this.directionalLight&&(this.directionalLight.destroy(),this.directionalLight=null),this.cubeCamera&&(this.cubeCamera.destroy(),this.cubeCamera=null),this.cubeEntity&&(this.cubeEntity.destroy(),this.cubeEntity=null),this.cubeMaterial&&(this.cubeMaterial.destroy(),this.cubeMaterial=null),this.cubeRoot&&(this.cubeRoot.destroy(),this.cubeRoot=null),this.cubeLayer){const t=this.app.scene.layers,e=t.getLayerById(this.cubeLayer.id);e&&t.remove(e),this.cubeLayer=null}this.useParentDiv&&this.separateCanvas&&(this.separateCanvas.parentElement&&this.separateCanvas.parentElement.removeChild(this.separateCanvas),this.separateCanvas=null,this.parentDiv=null),this.app=this.mainApp,this.initialized=!1}destroy(){if(this.initialized)try{this.cleanup()}catch(t){this.initialized=!1}}isInitialized(){return this.initialized}getMinimumCanvasSize(){return this.useParentDiv?this.MIN_PARENT_DIV_SIZE:this.MIN_CANVAS_SIZE}isVisibleOnCanvas(){return this.visible&&this.initialized&&this.shouldShowCube()}getCanvasDimensions(){const t=this.app.graphicsDevice.canvas;return t?{width:t.width,height:t.height}:null}getViewport(){if(!this.cubeCamera||!this.cubeCamera.camera)return null;if(this.useParentDiv)return{x:0,y:0,width:1,height:1};const t=this.cubeCamera.camera.rect;return{x:t.x,y:t.y,width:t.z,height:t.w}}getCanvas(){return this.useParentDiv&&this.separateCanvas?this.separateCanvas:this.app.graphicsDevice.canvas}getParentDiv(){return this.parentDiv}isUsingParentDiv(){return this.useParentDiv}}const wz={enableStats:!1,autoFocus:!0,maxSplats:2e6,previewMode:!1,camera:{position:{x:0,y:0,z:10},target:{x:0,y:0,z:0},distance:10,minDistance:.1,maxDistance:1e5,orbitSensitivity:.3,panSensitivity:1,zoomSensitivity:.1},navigationCube:{enabled:!1,cubeSize:150,position:{x:0,y:0},padding:{x:50,y:100},transitionDuration:600,controlPointRadius:6,controlPointColor:{normal:"#ffffff",hover:"#FB7347"},continuousRotationSpeed:45}};function Az(t){if(!t)return null;try{return JSON.parse(t)}catch(t){return null}}function Cz(t){return"boolean"==typeof t?t:"string"==typeof t&&("true"===t.toLowerCase()||"1"===t)}function Mz(t,e=0){if("number"==typeof t)return t;if("string"==typeof t){const i=parseFloat(t);return isNaN(i)?e:i}return e}class Pz{constructor(t={}){this._app=null,this._mainCamera=null,this._orbitScript=null,this.emitEvent=null,this.initialized=!1,this.cubeRenderer=null,this.controlPointManager=null,this.transitionController=null;const e=wz.navigationCube;if(!e)throw new Error("NavigationCubeController: DEFAULT_CONFIG.navigationCube is not defined");this.config={...e,...t},this._enabled=this.config.enabled}get enabled(){return this._enabled}initialize(t,e,i,s){if(!this.initialized&&this._enabled&&t&&e&&i){this._app=t,this._mainCamera=e,this._orbitScript=i,this.emitEvent=s||null;try{this.cubeRenderer=new bz(t,this.config),this.cubeRenderer.initialize(),this.cubeRenderer.setResizeCallback(()=>{this.updateControlPointPositions()});const e=this.cubeRenderer.getCanvas()||t.graphicsDevice.canvas,s=this.cubeRenderer.getParentDiv();this.controlPointManager=new uD(this.config,e,this.onControlPointClick.bind(this),this.onControlPointPressStart.bind(this),this.onControlPointPressEnd.bind(this),s),this.controlPointManager.initialize(),this.updateControlPointPositions(),this.transitionController=new dD(i,this.config.transitionDuration),void 0!==this.config.continuousRotationSpeed&&this.transitionController.setContinuousRotationSpeed(this.config.continuousRotationSpeed),this.initialized=!0}catch(t){this.cleanup(),this.initialized=!1}}}update(t){if(this.initialized&&this._enabled&&!("number"!=typeof t||t<0)&&isFinite(t))try{this.cubeRenderer&&this.cubeRenderer.render(),this.transitionController&&this.transitionController.update(t)}catch(t){}}updateControlPointPositions(){if(!this.controlPointManager||!this.cubeRenderer)return;const t=this.cubeRenderer.getViewport();t?this.controlPointManager.updateControlPointPositions(t):this.controlPointManager.updateControlPointPositions()}onControlPointClick(t){if(this.initialized&&this._enabled)try{this.snapToView(t)}catch(t){}}onControlPointPressStart(t){if(this.initialized&&this._enabled)try{this.transitionController&&this.transitionController.startContinuousRotation(t),this.emitEvent&&this.emitEvent("navigation-cube:continuous-rotation-start",{direction:t})}catch(t){}}onControlPointPressEnd(t){if(this.initialized&&this._enabled)try{this.transitionController&&this.transitionController.stopContinuousRotation(),this.emitEvent&&this.emitEvent("navigation-cube:continuous-rotation-end",{direction:t})}catch(t){}}syncWithCamera(t,e){if(this.initialized&&this._enabled&&"number"==typeof t&&"number"==typeof e)try{this.cubeRenderer&&this.cubeRenderer.setRotation(t,e)}catch(t){}}async snapToView(t){if(!this.initialized||!this._enabled)return Promise.reject(new Error("NavigationCubeController not initialized or disabled"));if(![cD.TOP,cD.BOTTOM,cD.LEFT,cD.RIGHT].includes(t))return Promise.reject(new Error(`Invalid direction: ${t}`));try{if(this.transitionController?.isTransitionActive()&&this.transitionController.cancelTransition("interrupted"),this.controlPointManager){const e=this.controlPointManager.getControlPoint(t);if(e?.element){const t=e.element,i=t.style.transform;t.style.transition="transform 100ms ease-out",t.style.transform="scale(1.4)",setTimeout(()=>{t.style.transition="background-color 200ms ease-in-out, transform 200ms ease-in-out, box-shadow 200ms ease-in-out",t.style.transform=i},100)}}if(!this.transitionController)throw new Error("TransitionController not initialized");const e=this.transitionController.calculateTargetState(t);if(!this.transitionController.validateTargetState(e))throw new Error("Invalid target state calculated");this.emitEvent&&this.emitEvent("navigation-cube:view-change-start",{direction:t});try{await this.transitionController.startTransition(e),this.emitEvent&&this.emitEvent("navigation-cube:view-change-complete",{direction:t})}catch(e){throw this.emitEvent&&this.emitEvent("navigation-cube:view-change-cancel",{direction:t,reason:e.message||"unknown"}),e}}catch(e){return this.emitEvent&&this.emitEvent("navigation-cube:view-change-cancel",{direction:t,reason:e instanceof Error?e.message:"unknown error"}),Promise.reject(e)}}setEnabled(t){if(this._enabled!==t&&(this._enabled=t,this.initialized))try{t?(this.cubeRenderer?.setVisible(!0),this.controlPointManager?.setVisible(!0)):(this.cubeRenderer?.setVisible(!1),this.controlPointManager?.setVisible(!1),this.transitionController?.cancelTransition("disabled"))}catch(t){}}updateConfig(t){const e=this.validateConfig(t);if(this.config={...this.config,...e},this.initialized)try{void 0!==e.cubeSize&&this.cubeRenderer&&(this.cubeRenderer.updateSize(e.cubeSize),this.updateControlPointPositions()),void 0!==e.controlPointColor&&this.controlPointManager&&this.controlPointManager.updateColors(e.controlPointColor),void 0!==e.controlPointRadius&&this.controlPointManager&&this.controlPointManager.updateRadius(e.controlPointRadius),void 0===e.padding&&void 0===e.position&&void 0===e.cubeSize||!this.controlPointManager||this.updateControlPointPositions(),void 0!==e.transitionDuration&&this.transitionController&&this.transitionController.setDuration(e.transitionDuration),void 0!==e.continuousRotationSpeed&&this.transitionController&&this.transitionController.setContinuousRotationSpeed(e.continuousRotationSpeed)}catch(t){}}validateConfig(t){const e={};if(void 0!==t.cubeSize&&"number"==typeof t.cubeSize&&isFinite(t.cubeSize)&&(e.cubeSize=Math.max(50,Math.min(500,t.cubeSize)),e.cubeSize,t.cubeSize),void 0!==t.controlPointRadius&&"number"==typeof t.controlPointRadius&&isFinite(t.controlPointRadius)&&(e.controlPointRadius=Math.max(4,Math.min(20,t.controlPointRadius)),e.controlPointRadius,t.controlPointRadius),void 0!==t.transitionDuration&&"number"==typeof t.transitionDuration&&isFinite(t.transitionDuration)&&(e.transitionDuration=Math.max(100,Math.min(3e3,t.transitionDuration)),e.transitionDuration,t.transitionDuration),void 0!==t.padding&&"object"==typeof t.padding&&null!==t.padding&&"number"==typeof t.padding.x&&"number"==typeof t.padding.y){const i=Math.max(0,Math.min(500,t.padding.x)),s=Math.max(0,Math.min(500,t.padding.y));e.padding={x:i,y:s},i!==t.padding.x||t.padding.y}if(void 0!==t.position&&"object"==typeof t.position&&null!==t.position&&"number"==typeof t.position.x&&"number"==typeof t.position.y){const i=Math.max(0,Math.min(1,t.position.x)),s=Math.max(0,Math.min(1,t.position.y));e.position={x:i,y:s},i!==t.position.x||t.position.y}return void 0!==t.controlPointColor&&"object"==typeof t.controlPointColor&&null!==t.controlPointColor&&"string"==typeof t.controlPointColor.normal&&"string"==typeof t.controlPointColor.hover&&this.isValidColor(t.controlPointColor.normal)&&this.isValidColor(t.controlPointColor.hover)&&(e.controlPointColor={normal:t.controlPointColor.normal,hover:t.controlPointColor.hover}),void 0!==t.enabled&&"boolean"==typeof t.enabled&&(e.enabled=t.enabled),void 0!==t.continuousRotationSpeed&&"number"==typeof t.continuousRotationSpeed&&isFinite(t.continuousRotationSpeed)&&(e.continuousRotationSpeed=Math.max(10,Math.min(180,t.continuousRotationSpeed)),e.continuousRotationSpeed,t.continuousRotationSpeed),e}isValidColor(t){if(/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(t))return!0;if(/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/i.test(t))return!0;if(/^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*[\d.]+\s*)?\)$/i.test(t))return!0;return!!["white","black","red","green","blue","yellow","orange","purple","pink","gray","grey","transparent"].includes(t.toLowerCase())}cancelTransition(t="manual-interaction"){if(this.initialized)try{this.transitionController&&this.transitionController.cancelTransition(t)}catch(t){}}onCanvasResize(){if(this.initialized&&this._enabled)try{this.cubeRenderer&&this.cubeRenderer.onCanvasResize(),this.controlPointManager&&this.updateControlPointPositions()}catch(t){}}cleanup(){this.transitionController&&(this.transitionController.cancelTransition("cleanup"),this.transitionController=null),this.controlPointManager&&(this.controlPointManager.destroy(),this.controlPointManager=null),this.cubeRenderer&&(this.cubeRenderer.destroy(),this.cubeRenderer=null),this._app=null,this._mainCamera=null,this._orbitScript=null}destroy(){if(this.initialized)try{this.cleanup(),this.initialized=!1}catch(t){this.initialized=!1}}getConfig(){return{...this.config}}isInitialized(){return this.initialized}}function Rz(t){return"number"==typeof t&&Number.isFinite(t)}function Lz(t,e){if(null==t)return e.clone();const i=t;if("function"==typeof i.clone&&Rz(i.x)&&Rz(i.y)&&Rz(i.z))return i;if(Array.isArray(t)){const[i,s,n]=t;return Rz(i)&&Rz(s)&&Rz(n)?new K(i,s,n):e.clone()}return Rz(i.x)&&Rz(i.y)&&Rz(i.z)?new K(i.x,i.y,i.z):Rz(i.r)&&Rz(i.g)&&Rz(i.b)?new K(i.r,i.g,i.b):e.clone()}const Dz=new WeakMap;function Iz(t){const e=Dz.get(t);if(e)return e;const i=function(t){const e=new Gi(t,{width:32,height:32,format:7,mipmaps:!1});e.addressU=0,e.addressV=0,e.minFilter=0,e.magFilter=0;const i=e.lock();let s=1337;const n=()=>(s^=s<<13,s^=s>>>17,s^=s<<5,(s>>>0)%256/255);for(let t=0;t<1024;t++){const e=Math.floor(255*n()),s=4*t;i[s+0]=e,i[s+1]=e,i[s+2]=e,i[s+3]=255}return e.unlock(),e.name="supersplat-blue-noise",e}(t);return Dz.set(t,i),i}const Oz=new K;class Nz{constructor(){this.boxes=new Map,this.nextId=0,this.app=null,this.parent=null,this.camera=null,this.onEvent=null,this.interactionEnabled=!0,this.selectedBoxId=null,this.cameraControlCallback=null,this.gizmoLayer=null,this.translateGizmo=null,this.attachedBoxId=null}initialize(t,e,i,s){this.app=t,this.parent=e,this.camera=i,this.onEvent=s||null,this.ensureTranslateGizmo()}setInteractionEnabled(t){this.interactionEnabled=t,this.updateGizmoAttachment()}setCameraControlCallback(t){this.cameraControlCallback=t}update(){this.ensureTranslateGizmo(),this.updateGizmoSize(),this.updateGizmoAttachment(),this.updateBoxShaderUniforms()}createBox(t={}){if(!this.app||!this.parent)return this.emitError(null,"BoxSelectionAPI not initialized","NOT_INITIALIZED"),null;const e="box_"+this.nextId++,i=t.sizeX??2,s=t.sizeY??2,n=t.sizeZ??2,r=Lz(t.color,new K(1,1,1)),a=t.visible??!0,o=new z_(e);o.addComponent("render",{type:"box",material:this.buildWireframeMaterial(r)}),o.setLocalScale(i,s,n),o.setLocalPosition(t.positionX??0,t.positionY??0,t.positionZ??0),o.render.castShadows=!1,o.render.receiveShadows=!1,o.render.enabled=a,this.parent.addChild(o);const l={id:e,entity:o,lenX:i,lenY:s,lenZ:n,color:r.clone(),visible:a};return this.boxes.set(e,l),this.selectedBoxId=e,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-created",{id:e}),e}removeBox(t){const e=this.boxes.get(t);if(!e)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1;if(e.entity.destroy(),this.boxes.delete(t),this.selectedBoxId===t){const t=this.boxes.keys().next().value;this.selectedBoxId=t??null}return this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-removed",{id:t}),!0}clear(){for(const t of Array.from(this.boxes.keys()))this.removeBox(t)}setBoxSize(t,e,i,s){const n=this.boxes.get(t);return n?e<=0||i<=0||s<=0?(this.emitError(t,"Box dimensions must be positive","INVALID_DIMENSIONS"),!1):(n.lenX=e,n.lenY=i,n.lenZ=s,n.entity.setLocalScale(e,i,s),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxSize(t){const e=this.boxes.get(t);return e?{x:e.lenX,y:e.lenY,z:e.lenZ}:null}setBoxPosition(t,e,i,s){const n=this.boxes.get(t);return n?(n.entity.setLocalPosition(e,i,s),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxPosition(t){const e=this.boxes.get(t);return e?e.entity.getLocalPosition().clone():null}setBoxColor(t,e,i,s){const n=this.boxes.get(t);if(!n)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1;n.color.set(e,i,s);const r=n.entity.render?.material;return r?.setParameter?.("lineColor",[n.color.x,n.color.y,n.color.z]),this.requestRender(),!0}getBoxColor(t){const e=this.boxes.get(t);return e?e.color.clone():null}showBox(t,e){const i=this.boxes.get(t);return i?(i.visible=e,i.entity.render.enabled=e,this.updateGizmoAttachment(),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxProperties(t){const e=this.boxes.get(t);return e?{id:t,size:{x:e.lenX,y:e.lenY,z:e.lenZ},position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()}:null}getAllBoxes(){const t=[];return this.boxes.forEach((e,i)=>{t.push({id:i,size:{x:e.lenX,y:e.lenY,z:e.lenZ},position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()})}),t}getSelectedBoxId(){return this.selectedBoxId}selectBox(t){return null===t?(this.selectedBoxId=null,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-selected",{id:null}),!0):this.boxes.has(t)?(this.selectedBoxId=t,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-selected",{id:t}),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}resetBox(t){const e=this.boxes.get(t);return e?(e.lenX=2,e.lenY=2,e.lenZ=2,e.entity.setLocalScale(2,2,2),e.entity.setLocalPosition(0,0,0),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}duplicateBox(t){const e=this.boxes.get(t);if(!e)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),null;const i=e.entity.getLocalPosition();return this.createBox({sizeX:e.lenX,sizeY:e.lenY,sizeZ:e.lenZ,positionX:i.x+1,positionY:i.y,positionZ:i.z,color:e.color.clone(),visible:e.visible})}getBoxAtPosition(t){return null}setInteractionEnabledForBox(t,e){}requestRender(){const t=this.app;t&&(t.renderNextFrame=!0)}ensureTranslateGizmo(){if(this.app&&this.camera&&this.camera.camera){if(!this.gizmoLayer){this.gizmoLayer=this.app.scene.layers.getLayerByName("Gizmo"),this.gizmoLayer||(this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0}),this.app.scene.layers.push(this.gizmoLayer));const t=this.camera.camera;t&&Array.isArray(t.layers)&&!t.layers.includes(this.gizmoLayer.id)&&(t.layers=t.layers.concat([this.gizmoLayer.id]))}if(!this.translateGizmo){const t=this.camera.camera;this.translateGizmo=new bL(t,this.gizmoLayer),this.translateGizmo.enabled=!0,this.translateGizmo.on("render:update",()=>{this.requestRender()}),this.translateGizmo.on("transform:start",()=>{this.cameraControlCallback?.(!1),this.requestRender()}),this.translateGizmo.on("transform:move",()=>{const t=this.selectedBoxId;t&&this.boxes.has(t)&&this.emitEvent("box-moved",{id:t,position:this.boxes.get(t).entity.getLocalPosition().clone()}),this.requestRender()}),this.translateGizmo.on("transform:end",()=>{this.cameraControlCallback?.(!0),this.requestRender()}),this.updateGizmoSize()}}}updateGizmoSize(){if(!(this.translateGizmo&&this.app&&this.camera&&this.camera.camera))return;const t=this.app.graphicsDevice.canvas,e=1===this.camera.camera.projection;this.translateGizmo.size=e?1125/Math.max(1,t.clientHeight):1200/Math.max(1,Math.max(t.clientWidth,t.clientHeight))}updateGizmoAttachment(){if(!this.translateGizmo)return;const t=this.interactionEnabled&&!!this.selectedBoxId,e=this.selectedBoxId?this.boxes.get(this.selectedBoxId):void 0;t&&e&&e.visible?this.attachedBoxId!==e.id&&(this.translateGizmo.attach([e.entity]),this.attachedBoxId=e.id,this.requestRender()):null!==this.attachedBoxId&&(this.translateGizmo.detach(),this.attachedBoxId=null,this.requestRender())}buildWireframeMaterial(t){const e=new Sp({uniqueName:"boxSelectionSupersplatWire",vertexGLSL:"\n attribute vec3 vertex_position;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n void main() {\n gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);\n }\n",fragmentGLSL:'\n // ray-box intersection in box space\n bool intersectBox(out float t0, out float t1, out int axis0, out int axis1, vec3 pos, vec3 dir, vec3 boxCen, vec3 boxLen)\n {\n bvec3 validDir = notEqual(dir, vec3(0.0));\n vec3 absDir = abs(dir);\n vec3 signDir = sign(dir);\n vec3 m = vec3(\n validDir.x ? 1.0 / absDir.x : 0.0,\n validDir.y ? 1.0 / absDir.y : 0.0,\n validDir.z ? 1.0 / absDir.z : 0.0\n ) * signDir;\n\n vec3 n = m * (pos - boxCen);\n vec3 k = abs(m) * boxLen;\n\n vec3 v0 = -n - k;\n vec3 v1 = -n + k;\n\n // replace invalid axes with -inf and +inf so the tests below ignore them\n v0 = mix(vec3(-1.0 / 0.0000001), v0, validDir);\n v1 = mix(vec3(1.0 / 0.0000001), v1, validDir);\n\n axis0 = (v0.x > v0.y) ? ((v0.x > v0.z) ? 0 : 2) : ((v0.y > v0.z) ? 1 : 2);\n axis1 = (v1.x < v1.y) ? ((v1.x < v1.z) ? 0 : 2) : ((v1.y < v1.z) ? 1 : 2);\n\n t0 = v0[axis0];\n t1 = v1[axis1];\n\n if (t0 > t1 || t1 < 0.0) {\n return false;\n }\n\n return true;\n }\n\n float calcDepth(in vec3 pos, in mat4 viewProjection) {\n vec4 v = viewProjection * vec4(pos, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n uniform sampler2D blueNoiseTex32;\n uniform mat4 matrix_viewProjection;\n uniform vec3 boxCen;\n uniform vec3 boxLen;\n\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n uniform vec2 targetSize;\n uniform vec3 lineColor;\n\n bool writeDepth(float alpha) {\n ivec2 uv = ivec2(gl_FragCoord.xy);\n ivec2 size = textureSize(blueNoiseTex32, 0);\n return alpha > texelFetch(blueNoiseTex32, uv % size, 0).y;\n }\n\n bool strips(vec3 pos, int axis) {\n // Thickness tuned to match SuperSplat viewer "thick wire"\n bvec3 b = lessThan(fract(pos * 2.0 + vec3(0.015)), vec3(0.06));\n b[axis] = false;\n return any(b);\n }\n\n void main() {\n vec2 clip = gl_FragCoord.xy / targetSize;\n vec3 worldNear = near_origin + near_x * clip.x + near_y * clip.y;\n vec3 worldFar = far_origin + far_x * clip.x + far_y * clip.y;\n vec3 rayDir = normalize(worldFar - worldNear);\n\n float t0, t1;\n int axis0, axis1;\n if (!intersectBox(t0, t1, axis0, axis1, worldNear, rayDir, boxCen, boxLen)) {\n discard;\n }\n\n vec3 frontPos = worldNear + rayDir * t0;\n bool front = t0 > 0.0 && strips(frontPos - boxCen, axis0);\n\n vec3 backPos = worldNear + rayDir * t1;\n bool back = strips(backPos - boxCen, axis1);\n\n if (front) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(frontPos, matrix_viewProjection) : 1.0;\n } else if (back) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(backPos, matrix_viewProjection) : 1.0;\n } else {\n discard;\n }\n }\n'});return e.cull=2,e.blendState=new Ji(!0,0,6,8,0,1,8),e.update(),e.setParameter("lineColor",[t.x,t.y,t.z]),e}updateBoxShaderUniforms(){if(!this.app)return;const t=this.app.graphicsDevice;t.scope.resolve("targetSize").setValue([t.width,t.height]),t.scope.resolve("blueNoiseTex32").setValue(Iz(t));for(const t of this.boxes.values()){const e=t.entity.render?.material;e?.setParameter&&(t.entity.getWorldTransform().getTranslation(Oz),e.setParameter("boxCen",[Oz.x,Oz.y,Oz.z]),e.setParameter("boxLen",[.5*t.lenX,.5*t.lenY,.5*t.lenZ]))}}emitEvent(t,e){this.onEvent&&this.onEvent(t,e)}emitError(t,e,i){this.emitEvent("box-selection-error",{boxId:t,message:e,code:i})}}const Fz=new K;class Uz{constructor(){this.spheres=new Map,this.nextId=0,this.app=null,this.parent=null,this.camera=null,this.onEvent=null,this.interactionEnabled=!0,this.selectedSphereId=null,this.cameraControlCallback=null,this.gizmoLayer=null,this.translateGizmo=null,this.attachedSphereId=null}initialize(t,e,i,s){this.app=t,this.parent=e,this.camera=i,this.onEvent=s||null,this.ensureTranslateGizmo()}setInteractionEnabled(t){this.interactionEnabled=t,this.updateGizmoAttachment()}setCameraControlCallback(t){this.cameraControlCallback=t}update(){this.ensureTranslateGizmo(),this.updateGizmoSize(),this.updateGizmoAttachment(),this.updateSphereShaderUniforms()}createSphere(t={}){if(!this.app||!this.parent)return this.emitError(null,"SphereSelectionAPI not initialized","NOT_INITIALIZED"),null;const e="sphere_"+this.nextId++,i=t.radius??1,s=Lz(t.color,new K(1,1,1)),n=t.visible??!0,r=new z_(e);r.addComponent("render",{type:"box",material:this.buildWireframeMaterial(s)}),r.setLocalScale(2*i,2*i,2*i),r.setLocalPosition(t.positionX??0,t.positionY??0,t.positionZ??0),r.render.castShadows=!1,r.render.receiveShadows=!1,r.render.enabled=n,this.parent.addChild(r);const a={id:e,entity:r,radius:i,color:s.clone(),visible:n};return this.spheres.set(e,a),this.selectedSphereId=e,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-created",{id:e}),e}removeSphere(t){const e=this.spheres.get(t);if(!e)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1;if(e.entity.destroy(),this.spheres.delete(t),this.selectedSphereId===t){const t=this.spheres.keys().next().value;this.selectedSphereId=t??null}return this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-removed",{id:t}),!0}clear(){for(const t of Array.from(this.spheres.keys()))this.removeSphere(t)}setSphereRadius(t,e){const i=this.spheres.get(t);return i?e<=0?(this.emitError(t,"Sphere radius must be positive","INVALID_RADIUS"),!1):(i.radius=e,i.entity.setLocalScale(2*e,2*e,2*e),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSphereRadius(t){const e=this.spheres.get(t);return e?e.radius:null}setSpherePosition(t,e,i,s){const n=this.spheres.get(t);return n?(n.entity.setLocalPosition(e,i,s),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSpherePosition(t){const e=this.spheres.get(t);return e?e.entity.getLocalPosition().clone():null}setSphereColor(t,e,i,s){const n=this.spheres.get(t);if(!n)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1;n.color.set(e,i,s);const r=n.entity.render?.material;return r?.setParameter?.("lineColor",[n.color.x,n.color.y,n.color.z]),this.requestRender(),!0}getSphereColor(t){const e=this.spheres.get(t);return e?e.color.clone():null}showSphere(t,e){const i=this.spheres.get(t);return i?(i.visible=e,i.entity.render.enabled=e,this.updateGizmoAttachment(),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSphereProperties(t){const e=this.spheres.get(t);return e?{id:t,radius:e.radius,position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()}:null}getAllSpheres(){const t=[];return this.spheres.forEach((e,i)=>{t.push({id:i,radius:e.radius,position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()})}),t}getSelectedSphereId(){return this.selectedSphereId}selectSphere(t){return null===t?(this.selectedSphereId=null,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-selected",{id:null}),!0):this.spheres.has(t)?(this.selectedSphereId=t,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-selected",{id:t}),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}resetSphere(t){const e=this.spheres.get(t);return e?(e.radius=1,e.entity.setLocalScale(2,2,2),e.entity.setLocalPosition(0,0,0),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}duplicateSphere(t){const e=this.spheres.get(t);if(!e)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),null;const i=e.entity.getLocalPosition();return this.createSphere({radius:e.radius,positionX:i.x+1,positionY:i.y,positionZ:i.z,color:e.color.clone(),visible:e.visible})}getSphereAtPosition(t){return null}setInteractionEnabledForSphere(t,e){}requestRender(){const t=this.app;t&&(t.renderNextFrame=!0)}ensureTranslateGizmo(){if(this.app&&this.camera&&this.camera.camera){if(!this.gizmoLayer){this.gizmoLayer=this.app.scene.layers.getLayerByName("Gizmo"),this.gizmoLayer||(this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0}),this.app.scene.layers.push(this.gizmoLayer));const t=this.camera.camera;t&&Array.isArray(t.layers)&&!t.layers.includes(this.gizmoLayer.id)&&(t.layers=t.layers.concat([this.gizmoLayer.id]))}if(!this.translateGizmo){const t=this.camera.camera;this.translateGizmo=new bL(t,this.gizmoLayer),this.translateGizmo.enabled=!0,this.translateGizmo.on("render:update",()=>{this.requestRender()}),this.translateGizmo.on("transform:start",()=>{this.cameraControlCallback?.(!1),this.requestRender()}),this.translateGizmo.on("transform:move",()=>{const t=this.selectedSphereId;t&&this.spheres.has(t)&&this.emitEvent("sphere-moved",{id:t,position:this.spheres.get(t).entity.getLocalPosition().clone()}),this.requestRender()}),this.translateGizmo.on("transform:end",()=>{this.cameraControlCallback?.(!0),this.requestRender()}),this.updateGizmoSize()}}}updateGizmoSize(){if(!(this.translateGizmo&&this.app&&this.camera&&this.camera.camera))return;const t=this.app.graphicsDevice.canvas,e=1===this.camera.camera.projection;this.translateGizmo.size=e?1125/Math.max(1,t.clientHeight):1200/Math.max(1,Math.max(t.clientWidth,t.clientHeight))}updateGizmoAttachment(){if(!this.translateGizmo)return;const t=this.interactionEnabled&&!!this.selectedSphereId,e=this.selectedSphereId?this.spheres.get(this.selectedSphereId):void 0;t&&e&&e.visible?this.attachedSphereId!==e.id&&(this.translateGizmo.attach([e.entity]),this.attachedSphereId=e.id,this.requestRender()):null!==this.attachedSphereId&&(this.translateGizmo.detach(),this.attachedSphereId=null,this.requestRender())}buildWireframeMaterial(t){const e=new Sp({uniqueName:"sphereSelectionSupersplatWire",vertexGLSL:"\n attribute vec3 vertex_position;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n void main() {\n gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);\n }\n",fragmentGLSL:'\n bool intersectSphere(out float t0, out float t1, vec3 pos, vec3 dir, vec4 sphere) {\n vec3 L = sphere.xyz - pos;\n float tca = dot(L, dir);\n\n float d2 = sphere.w * sphere.w - (dot(L, L) - tca * tca);\n if (d2 <= 0.0) {\n return false;\n }\n\n float thc = sqrt(d2);\n t0 = tca - thc;\n t1 = tca + thc;\n if (t1 <= 0.0) {\n return false;\n }\n\n return true;\n }\n\n float calcDepth(in vec3 pos, in mat4 viewProjection) {\n vec4 v = viewProjection * vec4(pos, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n vec2 calcAzimuthElev(in vec3 dir) {\n float azimuth = atan(dir.z, dir.x);\n float elev = asin(dir.y);\n return vec2(azimuth, elev) * 180.0 / 3.14159;\n }\n\n uniform sampler2D blueNoiseTex32;\n uniform mat4 matrix_viewProjection;\n uniform vec4 sphere;\n uniform vec3 lineColor;\n\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n uniform vec2 targetSize;\n\n bool writeDepth(float alpha) {\n vec2 uv = fract(gl_FragCoord.xy / 32.0);\n float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;\n return alpha > noise;\n }\n\n bool strips(vec3 lp) {\n vec2 ae = calcAzimuthElev(normalize(lp));\n\n float spacing = 180.0 / (2.0 * 3.14159 * sphere.w);\n // Thickness tuned to match SuperSplat viewer "thick wire"\n float size = 0.06;\n return fract(ae.x / spacing) < size ||\n fract(ae.y / spacing) < size;\n }\n\n void main() {\n vec2 clip = gl_FragCoord.xy / targetSize;\n vec3 worldNear = near_origin + near_x * clip.x + near_y * clip.y;\n vec3 worldFar = far_origin + far_x * clip.x + far_y * clip.y;\n\n vec3 rayDir = normalize(worldFar - worldNear);\n\n float t0, t1;\n if (!intersectSphere(t0, t1, worldNear, rayDir, sphere)) {\n discard;\n }\n\n vec3 frontPos = worldNear + rayDir * t0;\n bool front = t0 > 0.0 && strips(frontPos - sphere.xyz);\n\n vec3 backPos = worldNear + rayDir * t1;\n bool back = strips(backPos - sphere.xyz);\n\n if (front) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(frontPos, matrix_viewProjection) : 1.0;\n } else if (back) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(backPos, matrix_viewProjection) : 1.0;\n } else {\n discard;\n }\n }\n'});return e.cull=2,e.blendState=new Ji(!0,0,6,8,0,1,8),e.update(),e.setParameter("lineColor",[t.x,t.y,t.z]),e}updateSphereShaderUniforms(){if(!this.app)return;const t=this.app.graphicsDevice;t.scope.resolve("targetSize").setValue([t.width,t.height]),t.scope.resolve("blueNoiseTex32").setValue(Iz(t));for(const t of this.spheres.values()){const e=t.entity.render?.material;e?.setParameter&&(t.entity.getWorldTransform().getTranslation(Fz),e.setParameter("sphere",[Fz.x,Fz.y,Fz.z,t.radius]))}}emitEvent(t,e){this.onEvent&&this.onEvent(t,e)}emitError(t,e,i){this.emitEvent("sphere-selection-error",{sphereId:t,message:e,code:i})}}let Bz=0;class zz{constructor(t,e){this.readBytes=0,this.totalBytes=t,this.pull=async t=>{const i=await e(t);return this.readBytes+=i,i}}}const kz=(t,e)=>{const i=[];let s=0;const n=e.getReader();return new zz(t,async t=>{for(;s<t.byteLength;){const{done:t,value:e}=await n.read();if(t)break;i.push(e),s+=e.byteLength}let e=0;for(;e<t.byteLength&&i.length>0;){const n=i[0],r=Math.min(n.byteLength,t.byteLength-e);t.set(n.subarray(0,r),e),e+=r,s-=r,r<n.byteLength?i[0]=n.subarray(r):i.shift()}return e})};class Vz{constructor(t){this.source=t}async getReadStream(){const{source:t}=this;if(t instanceof ArrayBuffer)return kz(t.byteLength,(t=>{let e=0;return new ReadableStream({pull(i){if(e<t.byteLength){const s=Math.min(e+65536,t.byteLength),n=new Uint8Array(t,e,s-e);i.enqueue(n),e=s}else i.close()}})})(t));if(t instanceof Blob)return kz(t.size,t.stream());const e=t instanceof Response?t:await fetch(t instanceof Request?t:new Request(t));if(!e.ok)throw new Error(`Failed to fetch asset: ${e.status} ${e.statusText}`);if(!e.body)throw new Error("Response has no body");const i=e.headers.get("Content-Length");return kz(i?parseInt(i,10):0,e.body)}async arrayBuffer(){const{source:t}=this;if(t instanceof ArrayBuffer)return t;if(t instanceof Blob)return await t.arrayBuffer();const e=t instanceof Response?t:await fetch(t instanceof Request?t:new Request(t));if(!e.ok)throw new Error(`Failed to fetch asset: ${e.status} ${e.statusText}`);return await e.arrayBuffer()}}const Hz=async(t,e,i)=>{let s;return s=void 0===e||void 0===i?t.contents??t.url??t.filename:t.contents?t.contents.slice(e,i):await fetch(t.url??t.filename,{headers:{Range:`bytes=${e}-${i-1}`}}),new Vz(s)},Gz=1.414213562373095,Wz=.7071067811865475,Xz=t=>(t-.5)/.28209479177387814,Yz=t=>Math.log(t),qz=(t,e,i)=>(1-i)*t+i*e,jz=["x","y","z","nx","ny","nz","opacity","rot_0","rot_1","rot_2","rot_3","f_dc_0","f_dc_1","f_dc_2","scale_0","scale_1","scale_2"],$z=t=>new Float32Array(t),Kz=t=>{const e={};for(const i of jz)e[`property_${i}`]=$z(t);return e},Zz=(t,e,i,s,n,r,a)=>{const o=32*i;n.property_x[i]=t.getFloat32(o+0,!0),n.property_y[i]=t.getFloat32(o+4,!0),n.property_z[i]=t.getFloat32(o+8,!0),n.property_f_dc_0[i]=Xz(t.getUint8(o+12)/255),n.property_f_dc_1[i]=Xz(t.getUint8(o+13)/255),n.property_f_dc_2[i]=Xz(t.getUint8(o+14)/255),n.property_opacity[i]=(t=>-Math.log((1-t)/t))(t.getUint8(o+15)/255);const l=s.compressedScaleMin,h=s.compressedScaleMax;n.property_scale_0[i]=Yz(qz(l.x,h.x,t.getUint16(o+16,!0)/65535)),n.property_scale_1[i]=Yz(qz(l.y,h.y,t.getUint16(o+18,!0)/65535)),n.property_scale_2[i]=Yz(qz(l.z,h.z,t.getUint16(o+20,!0)/65535));const c=(t=>{const e=t>>30&3,i=(1023&t)/1023*Gz-Wz,s=(t>>10&1023)/1023*Gz-Wz,n=(t>>20&1023)/1023*Gz-Wz;let r=i*i+s*s+n*n;r=Math.min(1,r);const a=Math.sqrt(1-r);return 0===e?[a,i,s,n]:1===e?[i,a,s,n]:2===e?[i,s,a,n]:[i,s,n,a]})(t.getUint32(o+22,!0));if(n.property_rot_0[i]=c[3],n.property_rot_1[i]=c[0],n.property_rot_2[i]=c[1],n.property_rot_3[i]=c[2],n.property_nx[i]=t.getUint16(o+26,!0),n.property_ny[i]=t.getUint16(o+28,!0),n.property_nz[i]=t.getUint16(o+30,!0),a&&e&&r){const t=2*o,n=Array.from({length:15},(i,s)=>e.getUint32(t+4*s,!0)),{compressedSHMin:a,compressedSHMax:l}=s,h=n.map(t=>{return((t,e,i)=>new K(qz(t.x,e.x,i.x),qz(t.y,e.y,i.y),qz(t.z,e.z,i.z)))(a,l,new K((2047&(e=t))/2047,(e>>11&1023)/1023,(e>>21&2047)/2047));var e});for(let t=0;t<15;t++)r[t][i]=h[t].x,r[t+15][i]=h[t].y,r[t+30][i]=h[t].z}},Qz=async t=>{const{info:e,targetLod:i,isHasSH:s,dataFile:n,shFile:r,compressInfo:a,propertyOffset:o,properties:l,properties_f_rest:h}=t,c=e.lods[i],d=c.points,u=Number(c.offset),p=c.size;if(0===d)return o;const f=await Hz(n,u,u+p),m=new DataView(await f.arrayBuffer());let _;if(s){const t=await Hz(r,2*u,2*u+2*p);_=new DataView(await t.arrayBuffer())}const g=Kz(d),v=s?Array.from({length:45},()=>new Float32Array(d)):null;for(let t=0;t<d;t++)Zz(m,_,t,a,g,v,s);for(const t of jz)l[`property_${t}`].set(g[`property_${t}`],o);if(s&&h&&v)for(let t=0;t<45;t++)h[t].set(v[t],o);return o+d},Jz=async t=>{const e=await Hz(t),i=(new TextDecoder).decode(await e.arrayBuffer()),s=JSON.parse(i),n="Quality"===s.fileType&&!!t.mapFile("shcoef.bin"),r=(t=>{const e={};t.attributes.forEach(t=>{e[t.name]=t});const i=e.scale.min,s=e.scale.max,n=e.shcoef.min,r=e.shcoef.max;return{compressedScaleMin:new K(i[0],i[1],i[2]),compressedScaleMax:new K(s[0],s[1],s[2]),compressedSHMin:new K(n[0],n[1],n[2]),compressedSHMax:new K(r[0],r[1],r[2])}})(s),a=s.splats;let o=a.findIndex(t=>t<2e7);o<0&&(o=a.length-1);const l=a[o],h=t.mapFile("index.bin");if(!h)throw new Error("Failed to fetch index.bin");const c=new Vz(h.contents??h.url??h.filename),d=await c.arrayBuffer(),u=t.mapFile("data.bin"),p=n&&t.mapFile("shcoef.bin"),f=((t,e)=>{let i=0;const s=new DataView(t),n=[];for(;!(i>s.byteLength-1);){const t=s.getInt16(i,!0);i+=2;const r=s.getInt16(i,!0);i+=2;const a=[];for(let t=0;t<e.totalLevel;t++){const t=s.getInt32(i,!0);i+=4;const e=s.getBigInt64(i,!0);i+=8;const n=s.getInt32(i,!0);i+=4,a.push({points:t,offset:e,size:n})}const o={x:t,y:r,lods:a};n.push(o)}return n})(d,s);return await(async t=>{const{totalSplats:e,unitInfos:i,targetLod:s,isHasSH:n,dataFile:r,shFile:a,compressInfo:o}=t,l=Kz(e),h=n?Array.from({length:45},()=>$z(e)):null;let c=0;for(const t of i)c=await Qz({info:t,targetLod:s,isHasSH:n,dataFile:r,shFile:a,compressInfo:o,propertyOffset:c,properties:l,properties_f_rest:h});const d=new ym([{name:"vertex",count:e,properties:[...jz.map(t=>({type:"float",name:t,storage:l[`property_${t}`],byteSize:4})),...n&&h?h.map((t,e)=>({type:"float",name:`f_rest_${e}`,storage:t,byteSize:4})):[],{type:"float",name:"state",storage:new Uint8Array(e),byteSize:4}]}]);return d})({totalSplats:l,unitInfos:f,targetLod:o,isHasSH:n&&!!p,dataFile:u,shFile:p,compressInfo:r})},tk=async t=>{const e=await Hz(t);return(t=>{const e=t.byteLength/32,i=new DataView(t),s=new Float32Array(e),n=new Float32Array(e),r=new Float32Array(e),a=new Float32Array(e),o=new Float32Array(e),l=new Float32Array(e),h=new Float32Array(e),c=new Float32Array(e),d=new Float32Array(e),u=new Float32Array(e),p=new Float32Array(e),f=new Float32Array(e),m=new Float32Array(e),_=new Float32Array(e),g=new Uint8Array(e),v=.28209479177387814;let y;for(let t=0;t<e;t++)y=32*t,s[t]=i.getFloat32(y+0,!0),n[t]=i.getFloat32(y+4,!0),r[t]=i.getFloat32(y+8,!0),f[t]=Math.log(i.getFloat32(y+12,!0)),m[t]=Math.log(i.getFloat32(y+16,!0)),_[t]=Math.log(i.getFloat32(y+20,!0)),d[t]=(i.getUint8(y+24)/255-.5)/v,u[t]=(i.getUint8(y+25)/255-.5)/v,p[t]=(i.getUint8(y+26)/255-.5)/v,a[t]=-Math.log(255/i.getUint8(y+27)-1),o[t]=(i.getUint8(y+28)-128)/128,l[t]=(i.getUint8(y+29)-128)/128,h[t]=(i.getUint8(y+30)-128)/128,c[t]=(i.getUint8(y+31)-128)/128;return new ym([{name:"vertex",count:e,properties:[{type:"float",name:"x",storage:s,byteSize:4},{type:"float",name:"y",storage:n,byteSize:4},{type:"float",name:"z",storage:r,byteSize:4},{type:"float",name:"opacity",storage:a,byteSize:4},{type:"float",name:"rot_0",storage:o,byteSize:4},{type:"float",name:"rot_1",storage:l,byteSize:4},{type:"float",name:"rot_2",storage:h,byteSize:4},{type:"float",name:"rot_3",storage:c,byteSize:4},{type:"float",name:"f_dc_0",storage:d,byteSize:4},{type:"float",name:"f_dc_1",storage:u,byteSize:4},{type:"float",name:"f_dc_2",storage:p,byteSize:4},{type:"float",name:"scale_0",storage:f,byteSize:4},{type:"float",name:"scale_1",storage:m,byteSize:4},{type:"float",name:"scale_2",storage:_,byteSize:4},{type:"float",name:"state",storage:g,byteSize:4}]}])})(await e.arrayBuffer())};var ek;!function(t){t.camera="camera",t.model="model",t.splat="splat",t.shadow="shadow",t.debug="debug",t.other="other"}(ek||(ek={}));const ik=[ek.camera,ek.model,ek.splat,ek.shadow,ek.debug,ek.other];let sk=1,nk=class{constructor(t){this.scene=null,this.type=t,this.uid=sk++}destroy(){this.scene&&this.scene.remove(this)}add(){}remove(){}serialize(t){}onUpdate(t){}onPostUpdate(){}onPreRender(){}onPostRender(){}onAdded(t){}onRemoved(t){}move(t,e,i){}get worldBound(){return null}};var rk;!function(t){t[t.selected=1]="selected",t[t.locked=2]="locked",t[t.deleted=4]="deleted"}(rk||(rk={}));const ak=[0,4,8,12,1,5,9,13,2,6,10,14],ok=1536;class lk{constructor(t,e=4096){let i,s;const n=(e,n)=>{const r=new Gi(t,{name:"transformPalette",width:e,height:n,format:Nt,mipmaps:!1,addressU:1,addressV:1}),a=r.lock();r.unlock(),i&&(a.set(s),i.destroy()),i=r,s=a};this.getTransform=(t,e)=>{const i=e.data;for(let e=0;e<12;++e)i[ak[e]]=s[12*t+e]},this.setTransform=(t,e)=>{const n=e.data;for(let e=0;e<12;++e)s[12*t+e]=n[ak[e]];i.upload()};let r=1;this.alloc=(t=1)=>{const e=r;for(;r+t>s.length/12;)n(ok,2*i.height);return r+=t,e},this.free=(t=1)=>{r-=t},Object.defineProperty(this,"texture",{get:()=>i}),n(ok,Math.ceil(e/512)),this.setTransform(0,rt.IDENTITY)}}const hk=new K,ck=new K,dk=new K,uk=[-1,1].map(t=>[-1,1].map(e=>[-1,1].map(i=>[new K(t,e,i),new K(.75*t,e,i),new K(t,e,i),new K(t,.75*e,i),new K(t,e,i),new K(t,e,.75*i)]))).flat(3);class pk extends nk{constructor(t,e){super(ek.splat),this.numSplats=0,this.numDeleted=0,this.numLocked=0,this.numSelected=0,this.changedCounter=0,this.selectionBoundDirty=!0,this.localBoundDirty=!0,this.worldBoundDirty=!0,this._visible=!0,this.selectionAlpha=1,this._name="",this._tintClr=new H(1,1,1),this._temperature=0,this._saturation=1,this._brightness=0,this._blackPoint=0,this._whitePoint=1,this._transparency=1,this.measurePoints=[],this.measureSelection=-1;const i=t.resource,s=i.gsplatData,{device:n}=i;this._name=t.file.filename,this.asset=t,this.splatData=s,this.numSplats=s.numSplats,this.entity=new z_("splatEntitiy"),this.entity.setEulerAngles(e),this.entity.addComponent("gsplat",{asset:t});const r=this.entity.gsplat.instance;r.meshInstance.calculateSortDistance=(t,e,i)=>{const s=this.localBound,n=this.entity.getWorldTransform();let r;for(let t=0;t<8;++t){hk.x=s.center.x+s.halfExtents.x*(1&t?1:-1),hk.y=s.center.y+s.halfExtents.y*(2&t?1:-1),hk.z=s.center.z+s.halfExtents.z*(4&t?1:-1),n.transformPoint(hk,hk);const a=hk.sub(e).dot(i);(0===t||a>r)&&(r=a)}return r},this.splatData.getProp("state")||this.splatData.getElement("vertex").properties.push({type:"uchar",name:"state",storage:new Uint8Array(this.splatData.numSplats),byteSize:1}),this.splatData.getElement("vertex").properties.push({type:"ushort",name:"transform",storage:new Uint16Array(this.splatData.numSplats),byteSize:2});const{width:a,height:o}=i.colorTexture,l=(t,e)=>new Gi(n,{name:t,width:a,height:o,format:e,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});this.stateTexture=l("splatState",Jt),this.transformTexture=l("splatTransform",qt),this.transformPalette=new lk(n),new Ji(!0,0,1,8),this.rebuildMaterial=t=>{const{material:e}=r,{glsl:i}=e.shaderChunks;i.set("gsplatVS",'\n#include "gsplatCommonVS"\n\nuniform sampler2D splatState;\n\nuniform vec4 selectedClr;\nuniform vec4 lockedClr;\n\nuniform vec3 clrOffset;\nuniform vec4 clrScale;\n\nvarying mediump vec3 texCoordIsLocked; // store locked flat in z\nvarying mediump vec4 color;\n\n#if PICK_PASS\n uniform uint pickMode; // 0: add, 1: remove, 2: set\n#endif\n\nmediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);\n\nuniform float saturation;\n\nvec3 applySaturation(vec3 color) {\n vec3 grey = vec3(dot(color, vec3(0.299, 0.587, 0.114)));\n return grey + (color - grey) * saturation;\n}\n\nvoid main(void) {\n // read gaussian details\n SplatSource source;\n if (!initSource(source)) {\n gl_Position = discardVec;\n return;\n }\n\n // get per-gaussian edit state, discard if deleted\n uint vertexState = uint(texelFetch(splatState, source.uv, 0).r * 255.0 + 0.5) & 7u;\n\n #if OUTLINE_PASS\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n #elif UNDERLAY_PASS\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n #elif PICK_PASS\n if (pickMode == 0u) {\n // add: skip deleted, locked and selected splats\n if (vertexState != 0u) {\n gl_Position = discardVec;\n return;\n }\n } else if (pickMode == 1u) {\n // remove: skip deleted, locked and unselected splats\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n } else {\n // set: skip deleted and locked splats\n if ((vertexState & 6u) != 0u) {\n gl_Position = discardVec;\n return;\n }\n }\n #else\n if ((vertexState & 4u) != 0u) {\n gl_Position = discardVec;\n return;\n }\n #endif\n\n // get center\n vec3 modelCenter = readCenter(source);\n\n SplatCenter center;\n if (!initCenter(source, modelCenter, center)) {\n gl_Position = discardVec;\n return;\n }\n\n SplatCorner corner;\n if (!initCorner(source, center, corner)) {\n gl_Position = discardVec;\n return;\n }\n\n gl_Position = center.proj + vec4(corner.offset, 0.0, 0.0);\n\n // store texture coord and locked state\n texCoordIsLocked = vec3(corner.uv, (vertexState & 2u) != 0u ? 1.0 : 0.0);\n\n #if UNDERLAY_PASS\n color = readColor(source);\n color.xyz = mix(color.xyz, selectedClr.xyz * 0.2, selectedClr.a) * selectedClr.a;\n #elif PICK_PASS\n uvec4 bits = (uvec4(source.id) >> uvec4(0u, 8u, 16u, 24u)) & uvec4(255u);\n color = vec4(bits) / 255.0;\n // handle splat color\n #elif FORWARD_PASS\n // read color\n color = readColor(source);\n\n // evaluate spherical harmonics\n #if SH_BANDS > 0\n // calculate the model-space view direction\n vec3 dir = normalize(center.view * mat3(center.modelView));\n\n // read sh coefficients\n vec3 sh[SH_COEFFS];\n float scale;\n readSHData(source, sh, scale);\n\n // evaluate\n color.xyz += evalSH(sh, dir) * scale;\n #endif\n\n // apply tint/brightness\n color = color * clrScale + vec4(clrOffset, 0.0);\n\n // apply saturation\n color.xyz = applySaturation(color.xyz);\n\n // don\'t allow out-of-range alpha\n color.a = clamp(color.a, 0.0, 1.0);\n\n // apply tonemapping\n color = vec4(prepareOutputFromGamma(max(color.xyz, 0.0)), color.w);\n\n // apply locked/selected colors\n if ((vertexState & 2u) != 0u) {\n // locked\n color *= lockedClr;\n } else if ((vertexState & 1u) != 0u) {\n // selected\n color.xyz = mix(color.xyz, selectedClr.xyz * 0.8, selectedClr.a);\n }\n #endif\n}\n'),i.set("gsplatPS","\nvarying mediump vec3 texCoordIsLocked;\nvarying mediump vec4 color;\n\nuniform int mode; // 0: centers, 1: rings\nuniform float pickerAlpha;\nuniform float ringSize;\n\nconst float EXP4 = exp(-4.0);\nconst float INV_EXP4 = 1.0 / (1.0 - EXP4);\n\nfloat normExp(float x) {\n return (exp(x * -4.0) - EXP4) * INV_EXP4;\n}\n\nvoid main(void) {\n mediump float A = dot(texCoordIsLocked.xy, texCoordIsLocked.xy);\n\n if (A > 1.0) {\n discard;\n }\n\n #if OUTLINE_PASS\n gl_FragColor = vec4(1.0, 1.0, 1.0, mode == 0 ? exp(-A * 4.0) * color.a : 1.0);\n #else\n #ifdef PICK_PASS\n gl_FragColor = color;\n #else\n mediump float alpha = normExp(A) * color.a;\n\n if (texCoordIsLocked.z == 0.0 && ringSize > 0.0) {\n // rings mode\n if (A < 1.0 - ringSize) {\n alpha = max(0.05, alpha);\n } else {\n alpha = 0.6;\n }\n }\n\n gl_FragColor = vec4(color.xyz * alpha, alpha);\n #endif\n #endif\n}\n"),i.set("gsplatCenterVS","\nuniform mat4 matrix_model;\nuniform mat4 matrix_view;\nuniform mat4 matrix_projection;\n\nuniform highp usampler2D splatTransform; // per-splat index into transform palette\nuniform sampler2D transformPalette; // palette of transform matrices\n\nmat4 applyPaletteTransform(SplatSource source, mat4 model) {\n uint transformIndex = texelFetch(splatTransform, source.uv, 0).r;\n if (transformIndex == 0u) {\n return model;\n }\n\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n t[3] = vec4(0.0, 0.0, 0.0, 1.0);\n\n return model * transpose(t);\n}\n\n// project the model space gaussian center to view and clip space\nbool initCenter(SplatSource source, vec3 modelCenter, out SplatCenter center) {\n mat4 modelView = matrix_view * applyPaletteTransform(source, matrix_model);\n vec4 centerView = modelView * vec4(modelCenter, 1.0);\n\n // early out if splat is behind the camera\n if (centerView.z > 0.0) {\n return false;\n }\n\n vec4 centerProj = matrix_projection * centerView;\n\n // ensure gaussians are not clipped by camera near and far\n centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));\n\n center.view = centerView.xyz / centerView.w;\n center.proj = centerProj;\n center.projMat00 = matrix_projection[0][0];\n center.modelView = modelView;\n return true;\n}\n"),e.setDefine("SH_BANDS",`${Math.min(t,r.resource.shBands)}`),e.setParameter("splatState",this.stateTexture),e.setParameter("splatTransform",this.transformTexture),e.update()},this.selectionBoundStorage=new ut,this.localBoundStorage=r.resource.aabb,this.worldBoundStorage=r.meshInstance._aabb,r.meshInstance._updateAabb=!1,r.sorter.on("updated",()=>{this.changedCounter++})}destroy(){super.destroy(),this.entity.destroy(),this.asset.registry.remove(this.asset),this.asset.unload()}updateState(t=rk.selected){const e=this.splatData.getProp("state");this.stateTexture.lock().set(e),this.stateTexture.unlock();let i=0,s=0,n=0;for(let t=0;t<e.length;++t){const r=e[t];r&rk.deleted?n++:r&rk.locked?s++:r&rk.selected&&i++}this.numSplats=e.length-n,this.numLocked=s,this.numSelected=i,this.numDeleted=n,this.makeSelectionBoundDirty(),t&rk.deleted&&this.updateSorting(),this.scene.forceRender=!0,this.scene.events.fire("splat.stateChanged",this)}updatePositions(){const t=this.scene.dataProcessor.calcPositions(this),e=this.splatData.getProp("state"),{sorter:i}=this.entity.gsplat.instance,{centers:s}=i;for(let i=0;i<this.splatData.numSplats;++i)e[i]===rk.selected&&(s[3*i+0]=t[4*i],s[3*i+1]=t[4*i+1],s[3*i+2]=t[4*i+2]);this.updateSorting(),this.scene.forceRender=!0,this.scene.events.fire("splat.positionsChanged",this)}updateSorting(){const t=this.splatData.getProp("state");let e;if(this.makeLocalBoundDirty(),this.numSplats!==t.length){e=new Uint32Array(this.numSplats);let i=0;for(let s=0;s<t.length;++s)0===(t[s]&rk.deleted)&&(e[i++]=s)}this.entity.gsplat.instance.sorter.setMapping(e)}get worldTransform(){return this.entity.getWorldTransform()}set name(t){t!==this.name&&(this._name=t,this.scene.events.fire("splat.name",this))}get name(){return this._name}get filename(){return this.asset.file.filename}calcSplatWorldPosition(t,e){if(t>=this.splatData.numSplats)return!1;const{sorter:i}=this.entity.gsplat.instance,{centers:s}=i;return e.set(s[3*t+0],s[3*t+1],s[3*t+2]),this.worldTransform.transformPoint(e,e),!0}add(){this.scene.contentRoot.addChild(this.entity),this.scene.events.on("view.bands",this.rebuildMaterial,this),this.rebuildMaterial(this.scene.events.invoke("view.bands")),this.updateState()}remove(){this.scene.events.off("view.bands",this.rebuildMaterial,this),this.scene.contentRoot.removeChild(this.entity),this.scene.boundDirty=!0}serialize(t){t.packa(this.entity.getWorldTransform().data),t.pack(this.changedCounter),t.pack(this.visible),t.pack(this.tintClr.r,this.tintClr.g,this.tintClr.b),t.pack(this.temperature,this.saturation,this.brightness,this.blackPoint,this.whitePoint,this.transparency)}onPreRender(){const t=this.scene.events,e=this.scene.camera.renderOverlays&&t.invoke("selection")===this,i=t.invoke("camera.mode"),s=t.invoke("camera.overlay"),n=this.entity.gsplat.instance.material;n.setParameter("mode","rings"===i?1:0),n.setParameter("ringSize",e&&s&&"rings"===i?.04:0);const r=e&&!t.invoke("view.outlineSelection")?this.selectionAlpha:0,a=t.invoke("selectedClr"),o=t.invoke("unselectedClr"),l=t.invoke("lockedClr");n.setParameter("selectedClr",[a.r,a.g,a.b,a.a*r]),n.setParameter("unselectedClr",[o.r,o.g,o.b,o.a]),n.setParameter("lockedClr",[l.r,l.g,l.b,l.a]);const h=-this.blackPoint+this.brightness,c=1/(this.whitePoint-this.blackPoint);if(n.setParameter("clrOffset",[h,h,h]),n.setParameter("clrScale",[c*this.tintClr.r*(1+this.temperature),c*this.tintClr.g,c*this.tintClr.b*(1-this.temperature),this.transparency]),n.setParameter("saturation",this.saturation),n.setParameter("transformPalette",this.transformPalette.texture),this.visible&&e&&t.invoke("camera.bound")){const t=this.localBound,e=(new rt).setTRS(t.center,at.IDENTITY,t.halfExtents);e.mul2(this.entity.getWorldTransform(),e);for(let t=0;t<uk.length/2;t++){const i=uk[2*t],s=uk[2*t+1];e.transformPoint(i,ck),e.transformPoint(s,dk),this.scene.app.drawLine(ck,dk,H.WHITE,!0,this.scene.debugLayer)}}this.entity.enabled=this.visible}focalPoint(){return this.worldBound.center}move(t,e,i){const s=this.entity;t&&s.setLocalPosition(t),e&&s.setLocalRotation(e),i&&s.setLocalScale(i),this.makeWorldBoundDirty(),this.scene.events.fire("splat.moved",this)}makeSelectionBoundDirty(){this.selectionBoundDirty=!0,this.makeLocalBoundDirty()}makeLocalBoundDirty(){this.localBoundDirty=!0,this.makeWorldBoundDirty()}makeWorldBoundDirty(){this.worldBoundDirty=!0,this.scene.boundDirty=!0}get selectionBound(){const t=this.selectionBoundStorage;return this.selectionBoundDirty&&(this.scene.dataProcessor.calcBound(this,t,!0),this.selectionBoundDirty=!1),t}get localBound(){const t=this.localBoundStorage;return this.localBoundDirty&&(this.scene.dataProcessor.calcBound(this,t,!1),this.localBoundDirty=!1,this.entity.getWorldTransform().transformPoint(t.center,hk)),t}get worldBound(){const t=this.worldBoundStorage;return this.worldBoundDirty&&(t.setFromTransformedAabb(this.localBound,this.entity.getWorldTransform()),this.worldBoundDirty=!1),t}set visible(t){t!==this.visible&&(this._visible=t,this.scene.events.fire("splat.visibility",this))}get visible(){return this._visible}set tintClr(t){this._tintClr.equals(t)||(this._tintClr.set(t.r,t.g,t.b),this.scene.events.fire("splat.tintClr",this))}get tintClr(){return this._tintClr}set temperature(t){t!==this._temperature&&(this._temperature=t,this.scene.events.fire("splat.temperature",this))}get temperature(){return this._temperature}set saturation(t){t!==this._saturation&&(this._saturation=t,this.scene.events.fire("splat.saturation",this))}get saturation(){return this._saturation}set brightness(t){t!==this._brightness&&(this._brightness=t,this.scene.events.fire("splat.brightness",this))}get brightness(){return this._brightness}set blackPoint(t){t!==this._blackPoint&&(this._blackPoint=t,this.scene.events.fire("splat.blackPoint",this))}get blackPoint(){return this._blackPoint}set whitePoint(t){t!==this._whitePoint&&(this._whitePoint=t,this.scene.events.fire("splat.whitePoint",this))}get whitePoint(){return this._whitePoint}set transparency(t){t!==this._transparency&&(this._transparency=t,this.scene.events.fire("splat.transparency",this))}get transparency(){return this._transparency}getPivot(t,e,i){const{entity:s}=this;switch(t){case"center":i.set(s.getLocalPosition(),s.getLocalRotation(),s.getLocalScale());break;case"boundCenter":s.getLocalTransform().transformPoint((e?this.selectionBound:this.localBound).center,hk),i.set(hk,s.getLocalRotation(),s.getLocalScale())}}docSerialize(){const t=t=>[t.x,t.y,t.z];return{name:this.name,position:t(this.entity.getLocalPosition()),rotation:(t=>[t.x,t.y,t.z,t.w])(this.entity.getLocalRotation()),scale:t(this.entity.getLocalScale()),visible:this.visible,tintClr:(t=>[t.r,t.g,t.b,t.a])(this.tintClr),temperature:this.temperature,saturation:this.saturation,brightness:this.brightness,blackPoint:this.blackPoint,whitePoint:this.whitePoint,transparency:this.transparency}}docDeserialize(t){const{name:e,position:i,rotation:s,scale:n,visible:r,tintClr:a,temperature:o,saturation:l,brightness:h,blackPoint:c,whitePoint:d,transparency:u}=t;this.name=e,this.move(new K(i),new at(s),new K(n)),this.visible=r,this.tintClr=new H(a[0],a[1],a[2],a[3]),this.temperature=o??0,this.saturation=l??1,this.brightness=h,this.blackPoint=c,this.whitePoint=d,this.transparency=u}}const fk=new K(0,0,180),mk=new K(90,0,180);class _k{constructor(t,e,i){this.loadAllData=!0,this.app=t,this.events=e,this.defaultAnisotropy=i||1}async load(t){const e=e=>{const i=new T_(t.filename||t.url,"gsplat",{url:t.contents?`local-asset-${Date.now()}`:t.url??t.filename,filename:t.filename});return this.app.assets.add(i),i.resource=new Rm(this.app.graphicsDevice,e),i};t.animationFrame||this.events.fire("startSpinner");try{const i=(t.filename||t.url).toLowerCase();let s,n=fk;return i.endsWith(".splat")?s=e(await tk(t)):i.endsWith(".lcc")?(s=e(await Jz(t)),n=mk):s=await((t,e)=>{const i=e.contents&&(e.contents instanceof Response?e.contents:new Response(e.contents)),s={url:i?"local-asset-"+Bz++:e.url??e.filename,filename:e.filename,contents:i},n={decompress:!0,reorder:!e.animationFrame},r={mapUrl:e.mapUrl};return new Promise((i,a)=>{const o=new T_(e.filename||e.url,"gsplat",s,n,r);o.on("load:data",t=>{if(t instanceof ym&&t.getProp("scale_0")&&t.getProp("scale_1")&&!t.getProp("scale_2")){const e=new Float32Array(t.numSplats).fill(Math.log(1e-6));t.addProp("scale_2",e);const i=t.getElement("vertex").properties;i.splice(i.findIndex(t=>"scale_1"===t.name)+1,0,i.splice(i.length-1,1)[0])}}),o.on("load",()=>{const t=o.resource.gsplatData,e=["x","y","z","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","f_dc_0","f_dc_1","f_dc_2","opacity"].filter(e=>!t.getProp(e));e.length>0?a(new Error(`This file does not contain gaussian splatting data. The following properties are missing: ${e.join(", ")}`)):i(o)}),o.on("error",t=>{a(t)}),t.add(o),t.load(o)})})(this.app.assets,t),new pk(s,n)}finally{t.animationFrame||this.events.fire("stopSpinner")}}}const gk=new K,vk=new K,yk=(t,e)=>{for(const i in e)t.resolve(i).setValue(e[i])};class Sk{constructor(t){this.viewProjectionMat=new rt,this.splatParams=new Int32Array(3),this.device=t,this.dummyTexture=new Gi(t,{width:1,height:1,format:7});const e=(e,i,s,n)=>new Gi(t,{name:e,width:i,height:s,format:n,mipmaps:!1,addressU:1,addressV:1});this.copyShader=th.createShader(t,{uniqueName:"copyShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n ",fragmentGLSL:"\n uniform sampler2D colorTex;\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n gl_FragColor = texelFetch(colorTex, texel, 0);\n }\n "}),this.getIntersectResources=(()=>{let i=null,s=null,n=null,r=null;return(a,o)=>{i||(i=th.createShader(t,{uniqueName:"intersectByMaskShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform uvec2 splat_params; // splat texture width, num splats\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n uniform uvec2 output_params; // output width, height\n\n // 0: mask, 1: rect, 2: sphere\n uniform int mode;\n\n // mask params\n uniform sampler2D mask; // mask in alpha channel\n uniform vec2 mask_params; // mask width, height\n\n // rect params\n uniform vec4 rect_params; // rect x, y, width, height\n\n // sphere params\n uniform vec4 sphere_params; // sphere x, y, z, radius\n\n // box params\n uniform vec4 box_params; // box x, y, z\n uniform vec4 aabb_params; // len x, y, z\n\n void main(void) {\n // calculate output id\n uvec2 outputUV = uvec2(gl_FragCoord);\n uint outputId = (outputUV.x + outputUV.y * output_params.x) * 4u;\n\n vec4 clr = vec4(0.0);\n\n for (uint i = 0u; i < 4u; i++) {\n uint id = outputId + i;\n\n if (id >= splat_params.y) {\n continue;\n }\n\n // calculate splatUV\n ivec2 splatUV = ivec2(\n int(id % splat_params.x),\n int(id / splat_params.x)\n );\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n // transform to clip space and discard if outside\n vec3 world = (matrix_model * vec4(center, 1.0)).xyz;\n vec4 clip = matrix_viewProjection * vec4(world, 1.0);\n vec3 ndc = clip.xyz / clip.w;\n\n // skip offscreen fragments\n if (!any(greaterThan(abs(ndc), vec3(1.0)))) {\n if (mode == 0) {\n // select by mask\n ivec2 maskUV = ivec2((ndc.xy * vec2(0.5, -0.5) + 0.5) * mask_params);\n clr[i] = texelFetch(mask, maskUV, 0).a < 1.0 ? 0.0 : 1.0;\n } else if (mode == 1) {\n // select by rect\n clr[i] = all(greaterThan(ndc.xy * vec2(1.0, -1.0), rect_params.xy)) && all(lessThan(ndc.xy * vec2(1.0, -1.0), rect_params.zw)) ? 1.0 : 0.0;\n } else if (mode == 2) {\n // select by sphere\n clr[i] = length(world - sphere_params.xyz) < sphere_params.w ? 1.0 : 0.0;\n } else if (mode == 3) {\n // select by box\n vec3 relativePosition = world - box_params.xyz;\n bool isInsideCube = true;\n if (relativePosition.x < -aabb_params.x || relativePosition.x > aabb_params.x) {\n isInsideCube = false;\n }\n if (relativePosition.y < -aabb_params.y || relativePosition.y > aabb_params.y) {\n isInsideCube = false;\n }\n if (relativePosition.z < -aabb_params.z || relativePosition.z > aabb_params.z) {\n isInsideCube = false;\n }\n clr[i] = isInsideCube ? 1.0 : 0.0;\n }\n }\n }\n\n gl_FragColor = clr;\n }\n"}));const l=Math.max(1,Math.floor(a/2)),h=Math.ceil(o/(4*l));return s&&s.width===l&&s.height===h||(s&&(s.destroy(),n.destroy()),s=e("intersectTexture",l,h,7),n=new Ss({colorBuffer:s,depth:!1}),r=new Uint8Array(l*h*4)),{shader:i,texture:s,renderTarget:n,data:r}}})(),this.getBoundResources=(()=>{let i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null;return c=>(i||(i=th.createShader(t,{uniqueName:"calcBoundShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform sampler2D splatState; // per-splat state\n uniform highp ivec3 splat_params; // texture width, texture height, num splats\n uniform highp uint mode; // 0: selected, 1: visible\n\n // calculate min and max for a single column of splats\n void main(void) {\n\n vec3 boundMin = vec3(1e6);\n vec3 boundMax = vec3(-1e6);\n\n for (int id = 0; id < splat_params.y; id++) {\n // calculate splatUV\n ivec2 splatUV = ivec2(gl_FragCoord.x, id);\n\n // skip out-of-range splats\n if ((splatUV.x + splatUV.y * splat_params.x) >= splat_params.z) {\n continue;\n }\n\n // read splat state\n uint state = uint(texelFetch(splatState, splatUV, 0).r * 255.0);\n\n // skip deleted or locked splats\n if (((mode == 0u) && (state != 1u)) || ((mode == 1u) && ((state & 4u) != 0u))) {\n continue;\n }\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n boundMin = min(boundMin, mix(center, boundMin, isinf(center)));\n boundMax = max(boundMax, mix(center, boundMax, isinf(center)));\n }\n\n pcFragColor0 = vec4(boundMin, 0.0);\n pcFragColor1 = vec4(boundMax, 0.0);\n }\n"})),s&&s.width===c||(s&&(s.destroy(),n.destroy(),r.destroy(),a.destroy(),o.destroy()),s=e("calcBoundMin",c,1,Nt),n=e("calcBoundMax",c,1,Nt),r=new Ss({colorBuffers:[s,n],depth:!1}),o=new Ss({colorBuffer:n,depth:!1}),a=new Ss({colorBuffer:s,depth:!1}),l=new Float32Array(4*c),h=new Float32Array(4*c)),{shader:i,minTexture:s,maxTexture:n,renderTarget:r,minRenderTarget:a,maxRenderTarget:o,minData:l,maxData:h})})(),this.getPositionResources=(()=>{let i=null,s=null,n=null,r=null;return(a,o,l)=>(i||(i=th.createShader(t,{uniqueName:"calcPositionShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform ivec2 splat_params; // splat texture width, num splats\n\n void main(void) {\n // calculate output id\n ivec2 splatUV = ivec2(gl_FragCoord);\n\n // skip if splat index is out of bounds\n if (splatUV.x + splatUV.y * splat_params.x >= splat_params.y) {\n discard;\n }\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n gl_FragColor = vec4(center, 0.0);\n }\n"})),s&&s.width===a&&s.height===o||(s&&(s.destroy(),n.destroy()),s=e("positionTex",a,o,Nt),n=new Ss({colorBuffer:s,depth:!1}),r=new Float32Array(a*o*4)),{shader:i,texture:s,renderTarget:n,data:r})})()}intersect(t,e){const{device:i}=this,{scope:s}=i,n=e.splatData.numSplats,r=e.entity.gsplat.instance.resource.transformATexture,a=e.transformTexture,o=e.transformPalette.texture,l=e.scene.camera.entity.camera;this.viewProjectionMat.mul2(l.projectionMatrix,l.viewMatrix);const h=this.getIntersectResources(r.width,n);yk(s,{transformA:r,splatTransform:a,transformPalette:o,splat_params:[r.width,n],matrix_model:e.entity.getWorldTransform().data,matrix_viewProjection:this.viewProjectionMat.data,output_params:[h.texture.width,h.texture.height]});const c=t;c.mask?yk(s,{mode:0,mask:c.mask,mask_params:[c.mask.width,c.mask.height]}):yk(s,{mask:this.dummyTexture,mask_params:[0,0]});const d=t;d.rect?yk(s,{mode:1,rect_params:[2*d.rect.x1-1,2*d.rect.y1-1,2*d.rect.x2-1,2*d.rect.y2-1]}):yk(s,{rect_params:[0,0,0,0]});const u=t;u.sphere?yk(s,{mode:2,sphere_params:[u.sphere.x,u.sphere.y,u.sphere.z,u.sphere.radius]}):yk(s,{sphere_params:[0,0,0,0]});const p=t;p.box?yk(s,{mode:3,box_params:[p.box.x,p.box.y,p.box.z,0],aabb_params:[.5*p.box.lenx,.5*p.box.leny,.5*p.box.lenz,0]}):yk(s,{box_params:[0,0,0,0],aabb_params:[0,0,0,0]}),i.setBlendState(Ji.NOBLEND),lh(i,h.renderTarget,h.shader);return i.readPixels(0,0,h.texture.width,h.texture.height,h.data),h.data}calcBound(t,e,i){const s=t.scene.graphicsDevice,{scope:n}=s,r=t.splatData.numSplats,a=t.entity.gsplat.instance.resource.transformATexture,o=t.transformTexture,l=t.transformPalette.texture,h=t.stateTexture;this.splatParams[0]=a.width,this.splatParams[1]=a.height,this.splatParams[2]=r;const c=this.getBoundResources(a.width);yk(n,{transformA:a,splatTransform:o,transformPalette:l,splatState:h,splat_params:this.splatParams,mode:i?0:1});const d=s;s.setBlendState(Ji.NOBLEND),lh(s,c.renderTarget,c.shader),d.gl.readPixels(0,0,a.width,1,c.minTexture.impl._glFormat,c.minTexture.impl._glPixelType,c.minData),d.setRenderTarget(c.maxRenderTarget),d.updateBegin(),d.gl.readPixels(0,0,a.width,1,c.maxTexture.impl._glFormat,c.maxTexture.impl._glPixelType,c.maxData),d.updateEnd();const{minData:u,maxData:p}=c;gk.set(1/0,1/0,1/0),vk.set(-1/0,-1/0,-1/0);for(let t=0;t<a.width;t++){const e=u[4*t],i=u[4*t+1],s=u[4*t+2];isFinite(e)&&(gk.x=Math.min(gk.x,e)),isFinite(i)&&(gk.y=Math.min(gk.y,i)),isFinite(s)&&(gk.z=Math.min(gk.z,s));const n=p[4*t],r=p[4*t+1],a=p[4*t+2];isFinite(n)&&(vk.x=Math.max(vk.x,n)),isFinite(r)&&(vk.y=Math.max(vk.y,r)),isFinite(a)&&(vk.z=Math.max(vk.z,a))}e.setMinMax(gk,vk)}calcPositions(t){const{device:e}=this,{scope:i}=e,s=t.splatData.numSplats,n=t.entity.gsplat.instance.resource.transformATexture,r=t.transformTexture,a=t.transformPalette.texture,o=this.getPositionResources(n.width,n.height,s);yk(i,{transformA:n,splatTransform:r,transformPalette:a,splat_params:[n.width,s]}),e.setBlendState(Ji.NOBLEND),lh(e,o.renderTarget,o.shader);return e.gl.readPixels(0,0,o.texture.width,o.texture.height,o.texture.impl._glFormat,o.texture.impl._glPixelType,o.data),o.data}copyRt(t,e){const{device:i}=this;yk(i.scope,{colorTex:t.colorBuffer}),i.setBlendState(Ji.NOBLEND),lh(i,e,this.copyShader)}}class xk extends R{constructor(){super(...arguments),this.functions=new Map}function(t,e){if(this.functions.has(t))throw new Error(`error: function ${t} already exists`);this.functions.set(t,e)}invoke(t,...e){const i=this.functions.get(t);if(i)return i(...e)}}const Tk=new K,Ek=new K,bk=new K,wk=(t,e,i,s)=>Math.sqrt((i-t)**2+(s-e)**2);class Ak{constructor(t,e){const i=(e,i)=>{const s=t.azim-e*t.scene.config.controls.orbitSensitivity,n=t.elevation-i*t.scene.config.controls.orbitSensitivity;t.setAzimElev(s,n)},s=(e,i,s,n)=>{const r=t.entity.camera,a=t.distanceTween.value.distance*t.sceneRadius/t.fovFactor;r.screenToWorld(e,i,a,Tk),r.screenToWorld(e-s,i-n,a,Ek),bk.sub2(Ek,Tk),bk.add(t.focalPoint),t.setFocalPoint(bk)},n=e=>{t.setDistance(t.distance-(.999*t.distance+.001)*e*t.scene.config.controls.zoomSensitivity,2)};let r,a,o=-1;const l=new Set;let h,c,d,u=[];const p={ArrowUp:0,ArrowDown:0,ArrowLeft:0,ArrowRight:0};let f=!0;const m=t.scene.app.graphicsDevice.canvas;this.update=e=>{const i=p.ArrowRight-p.ArrowLeft,s=p.ArrowDown-p.ArrowUp;if(i||s){const n=e*t.flySpeed,r=t.entity.getWorldTransform(),a=r.getX().mulScalar(i*n),o=r.getZ().mulScalar(s*n),l=t.focalPoint.add(a).add(o);t.setFocalPoint(l)}};let _=null;const g=(e,i,s,n)=>{const r=e=>{t.scene.events.fire("camera.controller",i),s(e)};e.addEventListener(i,r,n),_=()=>{_?.(),e.removeEventListener(i,r)}};g(e,"pointerdown",t=>{if(f)if("mouse"===t.pointerType){if(-1!==o)return;e.setPointerCapture(t.pointerId),l.add(t.pointerId),o=t.button,r=t.offsetX,a=t.offsetY}else"touch"===t.pointerType&&(0===u.length&&(e.setPointerCapture(t.pointerId),l.add(t.pointerId)),u.push({x:t.offsetX,y:t.offsetY,id:t.pointerId}),2===u.length&&(h=.5*(u[0].x+u[1].x),c=.5*(u[0].y+u[1].y),d=wk(u[0].x,u[0].y,u[1].x,u[1].y)))}),g(e,"pointerup",t=>{if(!f){if(l.has(t.pointerId)){try{e.releasePointerCapture(t.pointerId)}catch{}l.delete(t.pointerId)}return o=-1,void(u=u.filter(e=>e.id!==t.pointerId))}"mouse"===t.pointerType?t.button===o&&(o=-1,e.releasePointerCapture(t.pointerId),l.delete(t.pointerId)):(u=u.filter(e=>e.id!==t.pointerId),0===u.length&&(e.releasePointerCapture(t.pointerId),l.delete(t.pointerId)))}),g(e,"pointermove",t=>{if(f)if("mouse"===t.pointerType){if(-1===o)return;const e=[1,4,2][o];if(0===(t.buttons&e))return void(o=-1);const l=t.offsetX-r,h=t.offsetY-a;r=t.offsetX,a=t.offsetY;const c=2===o?t.shiftKey||t.ctrlKey?"orbit":t.altKey||t.metaKey?"zoom":null:null;"orbit"===c||null===c&&0===o?i(l,h):"zoom"===c||null===c&&1===o?n(-.02*h):("pan"===c||null===c&&2===o)&&s(r,a,l,h)}else if(1===u.length){const e=u[0],s=t.offsetX-e.x,n=t.offsetY-e.y;e.x=t.offsetX,e.y=t.offsetY,i(s,n)}else if(2===u.length){const e=u[u.map(t=>t.id).indexOf(t.pointerId)];e.x=t.offsetX,e.y=t.offsetY;const i=.5*(u[0].x+u[1].x),r=.5*(u[0].y+u[1].y),a=wk(u[0].x,u[0].y,u[1].x,u[1].y);s(i,r,i-h,r-c),n(.01*(a-d)),h=i,c=r,d=a}}),g(e,"wheel",t=>{if(!f)return;const{deltaX:e,deltaY:r}=t;((t,e)=>Math.abs(t)>50&&0===e||Math.abs(e)>50&&0===t||0===t&&0!==e&&!Number.isInteger(e))(e,r)?n(-.002*r):t.ctrlKey||t.metaKey?n(-.02*r):t.shiftKey?s(t.offsetX,t.offsetY,e,r):i(e,r),t.preventDefault()},{passive:!1}),g(e,"dblclick",i=>{f&&(i.target!==e&&i.target!==m||t.pickFocalPoint(i.offsetX,i.offsetY))}),g(document,"keydown",t=>{f&&p.hasOwnProperty(t.key)&&t.target===document.body&&(p[t.key]=t.shiftKey?10:t.ctrlKey||t.metaKey||t.altKey?.1:1)}),g(document,"keyup",t=>{f&&p.hasOwnProperty(t.key)&&(p[t.key]=0)}),this.destroy=_,this.setEnabled=t=>{const i=!!t;i!==f&&(f=i,f||(()=>{o=-1,u=[];for(const t in p)p[t]=0;l.forEach(t=>{try{e.releasePointerCapture(t)}catch{}}),l.clear()})())}}}const Ck=t=>Math.pow(t-1,5)+1;class Mk{constructor(t){this.keys=Object.keys(t)}clone(t){const e={};return this.keys.forEach(i=>{e[i]=t[i]}),e}copy(t,e){this.keys.forEach(i=>{t[i]=e[i]})}lerp(t,e,i,s){this.keys.forEach(n=>{t[n]=e[n]+s*(i[n]-e[n])})}}class Pk{constructor(t){this.ops=new Mk(t),this.value=t,this.source=this.ops.clone(t),this.target=this.ops.clone(t),this.timer=0,this.transitionTime=0}goto(t,e=.25){0===e&&this.ops.copy(this.value,t),this.ops.copy(this.source,this.value),this.ops.copy(this.target,t),this.timer=0,this.transitionTime=e}update(t){this.timer<this.transitionTime?(this.timer=Math.min(this.timer+t,this.transitionTime),this.ops.lerp(this.value,this.source,this.target,Ck(this.timer/this.transitionTime))):this.ops.copy(this.value,this.target)}}const Rk=new K,Lk=new K,Dk=new _t,Ik=new vt,Ok=new K,Nk=new K,Fk=new K,Uk=new rt,Bk=new J;class zk extends nk{constructor(){super(ek.camera),this.focalPointTween=new Pk({x:0,y:.5,z:0}),this.azimElevTween=new Pk({azim:30,elev:-15}),this.distanceTween=new Pk({distance:1}),this.minElev=-90,this.maxElev=90,this.sceneRadius=1,this.flySpeed=5,this.targetSize=null,this.suppressFinalBlit=!1,this.renderOverlays=!0,this.manualControl=!1,this.entity=new z_("Camera"),this.entity.addComponent("camera")}set ortho(t){t!==this.ortho&&(this.entity.camera.projection=t?1:0,this.scene.events.fire("camera.ortho",t))}get ortho(){return 1===this.entity.camera.projection}set fov(t){this.entity.camera.fov=t}get fov(){return this.entity.camera.fov}set tonemapping(t){const e={none:6,linear:0,neutral:5,aces:3,aces2:4,filmic:1,hejl:2}[t];void 0!==e&&e!==this.entity.camera.toneMapping&&(this.entity.camera.toneMapping=e,this.scene.events.fire("camera.tonemapping",t))}get tonemapping(){switch(this.entity.camera.toneMapping){case 6:return"none";case 0:return"linear";case 5:return"neutral";case 3:return"aces";case 4:return"aces2";case 1:return"filmic";case 2:return"hejl"}return"none"}set near(t){this.entity.camera.nearClip=t}get near(){return this.entity.camera.nearClip}set far(t){this.entity.camera.farClip=t}get far(){return this.entity.camera.farClip}get focalPoint(){const t=this.focalPointTween.target;return new K(t.x,t.y,t.z)}get azimElev(){return this.azimElevTween.target}get azim(){return this.azimElev.azim}get elevation(){return this.azimElev.elev}get distance(){return this.distanceTween.target.distance}setFocalPoint(t,e=1){this.focalPointTween.goto(t,e*this.scene.config.controls.dampingFactor)}setAzimElev(t,e,i=1){t=((t,e)=>(t%e+e)%e)(t,360),e=Math.max(this.minElev,Math.min(this.maxElev,e));const s=this.azimElevTween;s.goto({azim:t,elev:e},i*this.scene.config.controls.dampingFactor),s.source.azim-t<-180?s.source.azim+=360:s.source.azim-t>180&&(s.source.azim-=360),this.ortho=!1}setDistance(t,e=1){const i=this.scene.config.controls;t=Math.max(i.minZoom,Math.min(i.maxZoom,t));this.distanceTween.goto({distance:t},e*i.dampingFactor)}setPose(t,e,i=1){Ok.sub2(e,t);const s=Ok.length(),n=Math.atan2(-Ok.x/s,-Ok.z/s)*V.RAD_TO_DEG,r=Math.asin(Ok.y/s)*V.RAD_TO_DEG;this.setFocalPoint(e,i),this.setAzimElev(n,r,i),this.setDistance(s/this.sceneRadius*this.fovFactor,i)}worldToScreen(t,e){const{camera:i}=this.entity.camera;Uk.mul2(i.projectionMatrix,i.viewMatrix),Bk.set(t.x,t.y,t.z,1),Uk.transformVec4(Bk,Bk),e.x=Bk.x/Bk.w*.5+.5,e.y=1-(Bk.y/Bk.w*.5+.5),e.z=Bk.z/Bk.w}add(){this.scene.cameraRoot.addChild(this.entity),this.entity.camera.layers=this.entity.camera.layers.concat([this.scene.shadowLayer.id,this.scene.debugLayer.id,this.scene.gizmoLayer.id]),this.scene.config.camera.debugRender&&this.entity.camera.setShaderPass(`debug_${this.scene.config.camera.debugRender}`);const t=document.getElementById("canvas-container")??(this.scene?this.scene.app.graphicsDevice.canvas:null);if(!t)throw new Error("Camera: no pointer target available for PointerController");this.controller=new Ak(this,t);const e=this.scene.config,i=e.controls;this.entity.camera.clearColor.set(0,0,0,0),this.minElev=180*i.minPolarAngle/Math.PI-90,this.maxElev=180*i.maxPolarAngle/Math.PI-90,this.scene.camera.entity.camera.toneMapping={linear:0,filmic:1,hejl:2,aces:3,aces2:4,neutral:5}[e.camera.toneMapping],this.scene.app.scene.exposure=e.camera.exposure,this.fov=e.camera.fov,this.setAzimElev(i.initialAzim,i.initialElev,0),this.setDistance(i.initialZoom,0);const{width:s,height:n}=this.scene.targetSize;this.picker=new SC(this.scene.app,s,n),this.picker.allocateRenderTarget=()=>{},this.picker.releaseRenderTarget=()=>{},this.scene.events.on("scene.boundChanged",this.onBoundChanged,this),this.updateCameraUniforms=()=>{const t=this.scene.graphicsDevice,e=this.entity,i=e.camera,s=(e,i)=>{t.scope.resolve(e).setValue([i.x,i.y,i.z])},n=i.camera.getFrustumCorners(-100),r=e.getWorldTransform();for(let t=0;t<n.length;t++)r.transformPoint(n[t],n[t]);0===i.projection?(s("near_origin",r.getTranslation()),s("near_x",K.ZERO),s("near_y",K.ZERO)):(s("near_origin",n[3]),s("near_x",Fk.sub2(n[0],n[3])),s("near_y",Fk.sub2(n[2],n[3]))),s("far_origin",n[7]),s("far_x",Fk.sub2(n[4],n[7])),s("far_y",Fk.sub2(n[6],n[7]))};const r=new URL(location.href),a=r.searchParams.get("focal");if(a){const t=a.toString().split(",");3===t.length&&this.setFocalPoint(new K(parseFloat(t[0]),parseFloat(t[1]),parseFloat(t[2])),0)}const o=r.searchParams.get("angles");if(o){const t=o.toString().split(",");2===t.length&&this.setAzimElev(parseFloat(t[0]),parseFloat(t[1]),0)}const l=r.searchParams.get("distance");l&&this.setDistance(parseFloat(l),0)}remove(){this.controller.destroy(),this.controller=null,this.entity.camera.layers=this.entity.camera.layers.filter(t=>t!==this.scene.shadowLayer.id),this.scene.cameraRoot.removeChild(this.entity),this.picker=null,this.scene.events.off("scene.boundChanged",this.onBoundChanged,this)}onBoundChanged(t){const e=this.distanceTween.value.distance*this.sceneRadius;this.sceneRadius=Math.max(.001,t.halfExtents.length()),this.setDistance(e/this.sceneRadius,0)}serialize(t){t.packa(this.entity.getWorldTransform().data),t.pack(this.fov,this.tonemapping,this.entity.camera.renderTarget?.width,this.entity.camera.renderTarget?.height)}rebuildRenderTargets(){const t=this.scene.graphicsDevice,{width:e,height:i}=this.targetSize??this.scene.targetSize,s=this.scene.events.invoke("camera.highPrecision")?Ot:7,n=this.entity.camera.renderTarget;if(n&&n.width===e&&n.height===i&&n.colorBuffer.format===s)return;n&&(n.destroyTextureBuffers(),n.destroy(),this.workRenderTarget.destroy(),this.workRenderTarget=null);const r=(e,i,s,n)=>new Gi(t,{name:e,width:i,height:s,format:n,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1}),a=r("cameraColor",e,i,s),o=r("cameraDepth",e,i,Ut),l=new Ss({colorBuffer:a,depthBuffer:o,flipY:!1,autoResolve:!1});this.entity.camera.renderTarget=l,this.entity.camera.horizontalFov=e>i;const h=r("workColor",e,i,7);this.workRenderTarget=new Ss({colorBuffer:h,depth:!1,autoResolve:!1}),this.picker.renderTarget=this.workRenderTarget,this.scene.events.fire("camera.resize",{width:e,height:i})}onUpdate(t){if(this.manualControl)return this.fitClippingPlanes(this.entity.getLocalPosition(),this.entity.forward),void this.entity.camera.camera._updateViewProjMat();this.controller.update(t),this.focalPointTween.update(t),this.azimElevTween.update(t),this.distanceTween.update(t);const e=this.azimElevTween.value,i=this.distanceTween.value;((t,e,i)=>{const s=i*V.DEG_TO_RAD,n=e*V.DEG_TO_RAD,r=Math.sin(-s),a=Math.cos(-s),o=Math.sin(-n),l=Math.cos(-n);t.set(-a*o,r,a*l)})(Rk,e.azim,e.elev),Lk.copy(Rk),Lk.mulScalar(i.distance*this.sceneRadius/this.fovFactor),Lk.add(this.focalPointTween.value),this.entity.setLocalPosition(Lk),this.entity.setLocalEulerAngles(e.elev,e.azim,0),this.fitClippingPlanes(this.entity.getLocalPosition(),this.entity.forward);const{camera:s}=this.entity;s.orthoHeight=this.distanceTween.value.distance*this.sceneRadius/this.fovFactor*(this.fov/90)*(s.horizontalFov?this.scene.targetSize.height/this.scene.targetSize.width:1),s.camera._updateViewProjMat()}setManualControl(t){this.manualControl=!!t;try{this.controller?.setEnabled?.(!this.manualControl)}catch{}}fitClippingPlanes(t,e){const i=this.scene.bound,s=i.halfExtents.length();Ok.sub2(i.center,t);const n=Ok.dot(e);n>0?(this.far=n+s,this.near=Math.max(1e-6,n<s?this.far/16384:n-s)):(this.far=2*s,this.near=this.far/16384)}onPreRender(){this.rebuildRenderTargets(),this.updateCameraUniforms()}onPostRender(){const t=this.scene.graphicsDevice,e=this.entity.camera.renderTarget;e.samples>1&&e.resolve(!0,!1),this.suppressFinalBlit||t.copyRenderTarget(e,null,!0,!1)}focus(t){const e=t?t.focalPoint:(()=>{for(const t of this.scene.elements)if(t.type===ek.splat){const e=t.focalPoint?.();if(e)return e}})()??this.scene.bound.center,i=(t?t.radius:this.scene.bound.halfExtents.length())/this.sceneRadius;this.setDistance(isFinite(i)?i:1,t?.speed??0),this.setFocalPoint(e,t?.speed??0)}get fovFactor(){const{width:t,height:e}=this.scene.targetSize,i=t&&e?this.entity.camera.horizontalFov?e/t:t/e:1,s=2*Math.atan(Math.tan(this.fov*V.DEG_TO_RAD*.5)*i);return Math.sin(.5*s)}getRay(t,e,i){const{entity:s,ortho:n,scene:r}=this,a=this.entity.getPosition();n?(s.camera.screenToWorld(t,e,-1,Ok),s.camera.screenToWorld(t,e,1,Nk),Nk.sub(Ok).normalize(),i.set(Ok,Nk)):(s.camera.screenToWorld(t,e,1,Ok),Ok.sub(a).normalize(),i.set(a,Ok))}intersect(t,e){const{scene:i}=this,s=i.canvas,n=t/s.clientWidth*i.targetSize.width,r=e/s.clientHeight*i.targetSize.height;this.getRay(t,e,Ik);const a=i.getElementsByType(ek.splat);let o=0;const l=new K;let h=null;for(let t=0;t<a.length;++t){const e=a[t];this.pickPrep(e,"set");const i=this.pick(n,r);if(-1!==i&&(e.calcSplatWorldPosition(i,Ok),Dk.setFromPointNormal(Ok,this.entity.forward),Dk.intersectsRay(Ik,Ok))){const t=Nk.sub2(Ok,Ik.origin).length();(!h||t<o)&&(o=t,l.copy(Ok),h=e)}}return h?{splat:h,position:l,distance:o}:null}pickFocalPoint(t,e){const i=this.intersect(t,e);if(i){const{scene:t}=this;this.setFocalPoint(i.position),this.setDistance(i.distance/this.sceneRadius*this.fovFactor),t.events.fire("camera.focalPointPicked",{camera:this,splat:i.splat,position:i.position})}}pickPrep(t,e){const{width:i,height:s}=this.scene.targetSize,n=this.scene.app.scene.layers.getLayerByName("World"),r=this.scene.graphicsDevice,a="rings"===this.scene.events.invoke("camera.mode")?0:.2,o=this.scene.getElementsByType(ek.splat);o.forEach(e=>{e.entity.enabled=e===t}),r.scope.resolve("pickerAlpha").setValue(a),r.scope.resolve("pickMode").setValue(["add","remove","set"].indexOf(e)),this.picker.resize(i,s),this.picker.prepare(this.entity.camera,this.scene.app.scene,[n]),o.forEach(t=>{t.entity.enabled=!0})}pick(t,e){return this.pickRect(t,e,1,1)[0]}pickRect(t,e,i,s){const n=this.scene.graphicsDevice,r=new Uint8Array(i*s*4);n.setRenderTarget(this.picker.renderTarget),n.updateBegin(),n.readPixels(t,this.picker.renderTarget.height-e-s,i,s,r),n.updateEnd();const a=[];for(let t=0;t<i*s;t++)a.push(r[4*t]|r[4*t+1]<<8|r[4*t+2]<<16|r[4*t+3]<<24);return a}docSerialize(){return{focalPoint:(t=>[t.x,t.y,t.z])(this.focalPointTween.target),azim:this.azim,elev:this.elevation,distance:this.distance,fov:this.fov,tonemapping:this.tonemapping}}docDeserialize(t){this.setFocalPoint(new K(t.focalPoint),0),this.setAzimElev(t.azim,t.elev,0),this.setDistance(t.distance,0),this.fov=t.fov,this.tonemapping=t.tonemapping}startOffscreenMode(t,e){this.targetSize={width:t,height:e},this.suppressFinalBlit=!0}endOffscreenMode(){this.targetSize=null,this.suppressFinalBlit=!1}}class kk extends nk{constructor(){super(ek.debug),this.blendState=new Ji(!1),this.depthState=new is(3,!0),this.visible=!0}add(){const t=this.scene.app.graphicsDevice;this.shader=th.createShader(t,{uniqueName:"infinite-grid",attributes:{vertex_position:ce},vertexGLSL:"\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n attribute vec2 vertex_position;\n\n varying vec3 worldFar;\n varying vec3 worldNear;\n\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n\n vec2 p = vertex_position * 0.5 + 0.5;\n worldNear = near_origin + near_x * p.x + near_y * p.y;\n worldFar = far_origin + far_x * p.x + far_y * p.y;\n }\n",fragmentGLSL:"\n uniform vec3 view_position;\n uniform mat4 matrix_viewProjection;\n uniform sampler2D blueNoiseTex32;\n\n uniform int plane; // 0: x (yz), 1: y (xz), 2: z (xy)\n\n vec4 planes[3] = vec4[3](\n vec4(1.0, 0.0, 0.0, 0.0),\n vec4(0.0, 1.0, 0.0, 0.0),\n vec4(0.0, 0.0, 1.0, 0.0)\n );\n\n vec3 colors[3] = vec3[3](\n vec3(1.0, 0.2, 0.2),\n vec3(0.2, 1.0, 0.2),\n vec3(0.2, 0.2, 1.0)\n );\n\n int axis0[3] = int[3](1, 0, 0);\n int axis1[3] = int[3](2, 2, 1);\n\n varying vec3 worldNear;\n varying vec3 worldFar;\n\n bool intersectPlane(inout float t, vec3 pos, vec3 dir, vec4 plane) {\n float d = dot(dir, plane.xyz);\n if (abs(d) < 1e-06) {\n return false;\n }\n\n float n = -(dot(pos, plane.xyz) + plane.w) / d;\n if (n < 0.0) {\n return false;\n }\n\n t = n;\n\n return true;\n }\n\n // https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8#1e7c\n float pristineGrid(in vec2 uv, in vec2 ddx, in vec2 ddy, vec2 lineWidth) {\n vec2 uvDeriv = vec2(length(vec2(ddx.x, ddy.x)), length(vec2(ddx.y, ddy.y)));\n bvec2 invertLine = bvec2(lineWidth.x > 0.5, lineWidth.y > 0.5);\n vec2 targetWidth = vec2(\n invertLine.x ? 1.0 - lineWidth.x : lineWidth.x,\n invertLine.y ? 1.0 - lineWidth.y : lineWidth.y\n );\n vec2 drawWidth = clamp(targetWidth, uvDeriv, vec2(0.5));\n vec2 lineAA = uvDeriv * 1.5;\n vec2 gridUV = abs(fract(uv) * 2.0 - 1.0);\n gridUV.x = invertLine.x ? gridUV.x : 1.0 - gridUV.x;\n gridUV.y = invertLine.y ? gridUV.y : 1.0 - gridUV.y;\n vec2 grid2 = smoothstep(drawWidth + lineAA, drawWidth - lineAA, gridUV);\n\n grid2 *= clamp(targetWidth / drawWidth, 0.0, 1.0);\n grid2 = mix(grid2, targetWidth, clamp(uvDeriv * 2.0 - 1.0, 0.0, 1.0));\n grid2.x = invertLine.x ? 1.0 - grid2.x : grid2.x;\n grid2.y = invertLine.y ? 1.0 - grid2.y : grid2.y;\n\n return mix(grid2.x, 1.0, grid2.y);\n }\n\n float calcDepth(vec3 p) {\n vec4 v = matrix_viewProjection * vec4(p, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n bool writeDepth(float alpha) {\n vec2 uv = fract(gl_FragCoord.xy / 32.0);\n float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;\n return alpha > noise;\n }\n\n void main(void) {\n vec3 p = worldNear;\n vec3 v = normalize(worldFar - worldNear);\n\n // intersect ray with the world xz plane\n float t;\n if (!intersectPlane(t, p, v, planes[plane])) {\n discard;\n }\n\n // calculate grid intersection\n vec3 worldPos = p + v * t;\n vec2 pos = plane == 0 ? worldPos.yz : (plane == 1 ? worldPos.xz : worldPos.xy);\n vec2 ddx = dFdx(pos);\n vec2 ddy = dFdy(pos);\n\n float epsilon = 1.0 / 255.0;\n\n // calculate fade\n float fade = 1.0 - smoothstep(400.0, 1000.0, length(worldPos - view_position));\n if (fade < epsilon) {\n discard;\n }\n\n vec2 levelPos;\n float levelSize;\n float levelAlpha;\n\n // 10m grid with colored main axes\n levelPos = pos * 0.1;\n levelSize = 2.0 / 1000.0;\n levelAlpha = pristineGrid(levelPos, ddx * 0.1, ddy * 0.1, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n vec3 color;\n vec2 loc = abs(levelPos);\n if (loc.x < levelSize) {\n if (loc.y < levelSize) {\n color = vec3(1.0);\n } else {\n color = colors[axis1[plane]];\n }\n } else if (loc.y < levelSize) {\n color = colors[axis0[plane]];\n } else {\n color = vec3(0.9);\n }\n gl_FragColor = vec4(color, levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n // 1m grid\n levelPos = pos;\n levelSize = 1.0 / 100.0;\n levelAlpha = pristineGrid(levelPos, ddx, ddy, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n gl_FragColor = vec4(vec3(0.7), levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n // 0.1m grid\n levelPos = pos * 10.0;\n levelSize = 1.0 / 100.0;\n levelAlpha = pristineGrid(levelPos, ddx * 10.0, ddy * 10.0, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n gl_FragColor = vec4(vec3(0.7), levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n discard;\n }\n"}),this.quadRender=new rh(this.shader);const e=new Ji(!0,0,6,8,0,1,8),i=[0,0,0],s=new rt;let n;this.scene.camera.entity.camera.on("preRenderLayer",(r,a)=>{const{scene:o}=this;if(this.visible&&r===o.debugLayer&&!a&&o.camera.renderOverlays){const{camera:r}=o;if(t.setBlendState(e),t.setCullMode(0),t.setDepthState(is.WRITEDEPTH),t.setStencilState(null,null),r.ortho){const t=(t,e)=>1-Math.abs(t.dot(e))<.001,e=r.entity.getWorldTransform().getZ();n=t(e,K.RIGHT)?0:t(e,K.BACK)?2:1}else n=1;const a=r.entity.getPosition();i[0]=a.x,i[1]=a.y,i[2]=a.z,s.mul2(r.entity.camera.projectionMatrix,r.entity.camera.viewMatrix),((t,e)=>{for(const i in e)t.resolve(i).setValue(e[i])})(t.scope,{plane:n,view_position:i,matrix_viewProjection:s.data}),this.quadRender.render()}})}remove(){this.shader.destroy(),this.quadRender.destroy()}serialize(t){t.pack(this.visible)}}class Vk extends nk{constructor(){super(ek.other),this.enabled=!0,this.clr=new H(1,1,1,.5),this.entity=new z_("outlineCamera"),this.entity.addComponent("camera"),this.entity.camera.setShaderPass("OUTLINE"),this.entity.camera.clearColor=new H(0,0,0,0)}add(){const t=this.scene.app.graphicsDevice,e=this.scene.overlayLayer.id;this.scene.events.on("selection.changed",(t,i)=>{i&&(i.entity.gsplat.layers=i.entity.gsplat.layers.filter(t=>t!==e)),t&&(t.entity.gsplat.layers=t.entity.gsplat.layers.concat([e]))}),this.entity.camera.layers=[e],this.scene.camera.entity.addChild(this.entity),this.shader=th.createShader(t,{uniqueName:"apply-outline",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform sampler2D outlineTexture;\n uniform float alphaCutoff;\n uniform vec4 clr;\n\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n\n // skip solid pixels\n if (texelFetch(outlineTexture, texel, 0).a > alphaCutoff) {\n discard;\n }\n\n for (int x = -2; x <= 2; x++) {\n for (int y = -2; y <= 2; y++) {\n if ((x != 0) && (y != 0) && (texelFetch(outlineTexture, texel + ivec2(x, y), 0).a > alphaCutoff)) {\n gl_FragColor = clr;\n return;\n }\n }\n }\n\n discard;\n }\n"}),this.quadRender=new rh(this.shader);const i=t.scope.resolve("outlineTexture"),s=t.scope.resolve("alphaCutoff"),n=t.scope.resolve("clr"),r=[1,1,1,1],a=this.scene.events;this.entity.camera.on("postRenderLayer",(e,o)=>{if(!this.entity.enabled||e!==this.scene.overlayLayer||!o)return;t.setBlendState(Ji.ALPHABLEND),t.setCullMode(0),t.setDepthState(is.NODEPTH),t.setStencilState(null,null);const l=a.invoke("selectedClr");r[0]=l.r,r[1]=l.g,r[2]=l.b,r[3]=l.a,i.setValue(this.entity.camera.renderTarget.colorBuffer),s.setValue("rings"===a.invoke("camera.mode")?0:.4),n.setValue(r);const h=t;h.setRenderTarget(this.scene.camera.entity.camera.renderTarget),h.updateBegin(),this.quadRender.render(),h.updateEnd()})}remove(){this.scene.camera.entity.removeChild(this.entity)}onPreRender(){const t=this.scene.camera.entity.camera,e=this.entity.camera;e.projection=t.projection,e.horizontalFov=t.horizontalFov,e.fov=t.fov,e.nearClip=t.nearClip,e.farClip=t.farClip,e.orthoHeight=t.orthoHeight,this.entity.enabled=this.enabled&&this.scene.events.invoke("view.outlineSelection"),this.entity.camera.renderTarget=this.scene.camera.workRenderTarget}}class Hk extends q_{constructor(t,e){super(t);const i=new $_;i.graphicsDevice=e.graphicsDevice,this.addComponentSystems(i),this.addResourceHandles(i),i.elementInput=e.elementInput,i.keyboard=e.keyboard,i.mouse=e.mouse,i.touch=e.touch,i.gamepads=e.gamepads,i.scriptPrefix=e.scriptPrefix,i.assetPrefix=e.assetPrefix,i.scriptsOrder=e.scriptsOrder,this.init(i)}addComponentSystems(t){t.componentSystems=[gv,tx,_T,ST,ME]}addResourceHandles(t){t.resourceHandlers=[IE,Db,Ib,vA,Hb,kb,dw]}}class Gk{constructor(t){this.packValue=t}pack(...t){for(let e=0;e<t.length;++e)this.packValue(t[e])}packa(t){for(let e=0;e<t.length;++e)this.packValue(t[e])}packVec3(t){this.pack(t.x,t.y,t.z)}packColor(t){this.pack(t.r,t.g,t.b,t.a)}}const Wk=new Set;class Xk{constructor(){this.states={},this.serializer=new Gk(t=>{this.activeValues.push(t)});for(let t=0;t<ik.length;++t)this.states[ik[t]]={elements:new Map,valueStart:[],valueCount:[],values:[]}}reset(){ik.forEach(t=>{const e=this.states[t];e.elements.clear(),e.valueStart.length=0,e.valueCount.length=0,e.values.length=0})}pack(t){const e=this.states[t.type],i=e.values.length;this.activeValues=e.values,t.serialize(this.serializer),e.elements.set(t,e.elements.size),e.valueStart.push(i),e.valueCount.push(e.values.length-i)}compare(t){function e(t,e){for(const i of t.keys())if(!e.has(i))return!0}function i(t,e){for(const i of t)if(e(i))return!0;return!1}const s={added:new Array,removed:new Array,moved:new Array,changed:new Array};return ik.forEach(n=>{const r=t.states[n],a=this.states[n],o=r.elements,l=a.elements;!function(t,e,i){t.clear();for(const s of e.keys())i.has(s)&&t.add(s)}(Wk,o,l),e(l,Wk)&&s.added.push(n),e(o,Wk)&&s.removed.push(n),i(Wk.values(),t=>o.get(t)!==l.get(t))&&s.moved.push(n),i(Wk.values(),t=>{const e=o.get(t),i=l.get(t),s=r.valueCount[e];if(s!==a.valueCount[i])return!0;const n=r.valueStart[e],h=a.valueStart[i],c=r.values,d=a.values;for(let t=0;t<s;++t)if(c[n+t]!==d[h+t])return!0;return!1})&&s.changed.push(n)}),s}}class Yk extends nk{constructor(){super(ek.debug)}add(){const t=this.scene.graphicsDevice,e=new Sp({uniqueName:"splatOverlayMaterial",attributes:{vertex_id:ce},vertexGLSL:"\n attribute uint vertex_id;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n uniform sampler2D splatState;\n uniform highp usampler2D splatPosition;\n uniform highp usampler2D splatTransform; // per-splat index into transform palette\n uniform sampler2D transformPalette; // palette of transform matrices\n\n uniform uvec2 texParams;\n\n uniform float splatSize;\n uniform vec4 selectedClr;\n uniform vec4 unselectedClr;\n\n varying vec4 varying_color;\n\n // calculate the current splat index and uv\n ivec2 calcSplatUV(uint index, uint width) {\n return ivec2(int(index % width), int(index / width));\n }\n\n void main(void) {\n ivec2 splatUV = calcSplatUV(vertex_id, texParams.x);\n uint splatState = uint(texelFetch(splatState, splatUV, 0).r * 255.0);\n\n if ((splatState & 6u) != 0u) {\n // deleted or locked (4 or 2)\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n gl_PointSize = 0.0;\n } else {\n mat4 model = matrix_model;\n \n // handle per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n t[3] = vec4(0.0, 0.0, 0.0, 1.0);\n\n model = matrix_model * transpose(t);\n }\n\n varying_color = (splatState == 1u) ? selectedClr : unselectedClr;\n\n vec3 center = uintBitsToFloat(texelFetch(splatPosition, splatUV, 0).xyz);\n\n gl_Position = matrix_viewProjection * model * vec4(center, 1.0);\n gl_PointSize = splatSize;\n }\n }\n",fragmentGLSL:"\n varying vec4 varying_color;\n\n void main(void) {\n gl_FragColor = varying_color;\n }\n"});e.blendType=2;const i=new gh(t),s=new Rh(i,e,null),n=this.scene.events,r=n=>{if(!n)return void(s.node=null);const r=n.splatData,a=new ms(t,[{semantic:ce,components:1,type:5,asInt:!0}]),o=new Uint32Array(r.numSplats);for(let t=0;t<r.numSplats;++t)o[t]=t;const l=new hs(t,a,r.numSplats,{usage:0,data:o.buffer});i.vertexBuffer&&(i.vertexBuffer.destroy(),i.vertexBuffer=null),i.vertexBuffer=l,i.primitive[0]={type:0,base:0,baseVertex:0,count:r.numSplats},e.setParameter("splatState",n.stateTexture),e.setParameter("splatPosition",n.entity.gsplat.instance.resource.transformATexture),e.setParameter("splatTransform",n.transformTexture),e.setParameter("texParams",[n.stateTexture.width,n.stateTexture.height]),e.update(),s.node=n.entity,this.splat=n};n.on("selection.changed",t=>{r(t)}),this.meshInstance=s}destroy(){this.meshInstance.material.destroy(),this.meshInstance.destroy()}onPreRender(){const t=this.scene.events,e=t.invoke("camera.splatSize");if(this.meshInstance.node&&this.scene.camera.renderOverlays&&e>0&&t.invoke("camera.overlay")&&"centers"===t.invoke("camera.mode")){const i=t.invoke("selectedClr"),s=t.invoke("unselectedClr"),{material:n}=this.meshInstance;n.setParameter("splatSize",e*window.devicePixelRatio),n.setParameter("selectedClr",[i.r,i.g,i.b,i.a]),n.setParameter("unselectedClr",[s.r,s.g,s.b,s.a]),n.setParameter("transformPalette",this.splat.transformPalette.texture),this.scene.app.drawMeshInstance(this.meshInstance)}}}class qk extends nk{constructor(){super(ek.other),this.enabled=!0,this.entity=new z_("underlayCamera"),this.entity.addComponent("camera"),this.entity.camera.setShaderPass("UNDERLAY"),this.entity.camera.clearColor=new H(0,0,0,0)}add(){const t=this.scene.app.graphicsDevice;this.entity.camera.layers=[this.scene.overlayLayer.id],this.scene.camera.entity.addChild(this.entity),this.shader=th.createShader(t,{uniqueName:"apply-underlay",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform sampler2D blitTexture;\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n\n gl_FragColor = texelFetch(blitTexture, texel, 0);\n }\n"}),this.quadRender=new rh(this.shader);const e=t.scope.resolve("blitTexture"),i=new Ji(!0,0,1,1,0,0,1);this.entity.camera.on("postRenderLayer",(s,n)=>{if(!this.entity.enabled||s!==this.scene.overlayLayer||!n)return;t.setBlendState(i),e.setValue(this.entity.camera.renderTarget.colorBuffer);const r=t;r.setRenderTarget(this.scene.camera.entity.camera.renderTarget),r.updateBegin(),this.quadRender.render(),r.updateEnd()})}remove(){this.scene.camera.entity.removeChild(this.entity)}onPreRender(){const t=this.scene.camera.entity.camera,e=this.entity.camera;e.projection=t.projection,e.horizontalFov=t.horizontalFov,e.fov=t.fov,e.nearClip=t.nearClip,e.farClip=t.farClip,e.orthoHeight=t.orthoHeight,this.entity.enabled=this.enabled&&!this.scene.events.invoke("view.outlineSelection"),this.entity.camera.renderTarget=this.scene.camera.workRenderTarget}}class jk{constructor(t,e,i,s){this.sceneState=[new Xk,new Xk],this.elements=[],this.boundStorage=new ut,this.boundDirty=!0,this.forceRender=!1,this.lockedRenderMode=!1,this.lockedRender=!1,this.canvasResize=null,this.targetSize={width:0,height:0},this.events=t,this.config=e,this.canvas=i,this.app=new Hk(i,{graphicsDevice:s}),this.app.autoRender=!1,this.app._allowResize=!1,this.app.scene.clusteredLightingEnabled=!1,this.app.off("prerender",this.app._firstBake,this.app),this.app.loader.getHandler("texture").imgParser.crossOrigin="anonymous",this.app.graphicsDevice.maxPixelRatio=window.devicePixelRatio;const n=new ResizeObserver(t=>{if(t.length>0){const e=t[0];if(e)if(e.devicePixelContentBoxSize)this.canvasResize={width:e.devicePixelContentBoxSize[0].inlineSize,height:e.devicePixelContentBoxSize[0].blockSize};else if(e.contentBoxSize.length>0){const t=window.devicePixelRatio;this.canvasResize={width:Math.ceil(e.contentBoxSize[0].inlineSize*t),height:Math.ceil(e.contentBoxSize[0].blockSize*t)}}this.forceRender=!0}}),r=window.document.getElementById("canvas-container")??this.canvas;r&&n.observe(r);const a=this.app.scene.layers.getLayerById(1);this.app.scene.layers.remove(a),this.app.scene.layers.insertOpaque(a,2),this.app.on("update",t=>this.onUpdate(t)),this.app.on("prerender",()=>this.onPreRender()),this.app.on("postrender",()=>this.onPostRender()),this.app.graphicsDevice.on("devicerestored",()=>{this.forceRender=!0}),this.app.scene.on(Ul,(t,e,i)=>{t.fire("preRenderLayer",e,i)}),this.app.scene.on(Bl,(t,e,i)=>{t.fire("postRenderLayer",e,i)}),this.backgroundLayer=new iu({enabled:!0,name:"Background Layer",opaqueSortMode:0,transparentSortMode:0}),this.shadowLayer=new iu({name:"Shadow Layer"}),this.debugLayer=new iu({enabled:!0,name:"Debug Layer",opaqueSortMode:0,transparentSortMode:0}),this.overlayLayer=new iu({name:"Overlay",clearDepthBuffer:!1,opaqueSortMode:0,transparentSortMode:0}),this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0});const o=this.app.scene.layers,l=o.getLayerByName("World"),h=o.getOpaqueIndex(l);o.insert(this.backgroundLayer,h),o.insert(this.shadowLayer,h+1),o.insert(this.debugLayer,h+1),o.push(this.overlayLayer),o.push(this.gizmoLayer),this.dataProcessor=new Sk(this.app.graphicsDevice),this.assetLoader=new _k(this.app,t,this.app.graphicsDevice.maxAnisotropy),this.contentRoot=new z_("contentRoot"),this.app.root.addChild(this.contentRoot),this.cameraRoot=new z_("cameraRoot"),this.app.root.addChild(this.cameraRoot),this.camera=new zk,this.add(this.camera),this.splatOverlay=new Yk,this.add(this.splatOverlay),this.grid=new kk,this.add(this.grid),this.outline=new Vk,this.add(this.outline),this.underlay=new qk,this.add(this.underlay)}start(){this.app.start()}clear(){this.getElementsByType(ek.splat).forEach(t=>{this.remove(t),t.destroy()})}add(t){t.scene||(t.scene=this,t.add(),this.elements.push(t),this.forEachElement(e=>e!==t&&e.onAdded(t)),this.events.fire("scene.elementAdded",t))}remove(t){t.scene===this&&(this.elements.splice(this.elements.indexOf(t),1),this.events.fire("scene.elementRemoved",t),this.forEachElement(e=>e.onRemoved(t)),t.remove(),t.scene=null)}get bound(){if(this.boundDirty){let t=!1;this.forEachElement(e=>{const i=e.worldBound;i&&(t?this.boundStorage.add(i):(t=!0,this.boundStorage.copy(i)))}),this.boundDirty=!1,this.events.fire("scene.boundChanged",this.boundStorage)}return this.boundStorage}getElementsByType(t){return this.elements.filter(e=>e.type===t)}get graphicsDevice(){return this.app.graphicsDevice}forEachElement(t){this.elements.forEach(t)}onUpdate(t){this.forEachElement(e=>e.onUpdate(t)),this.events.fire("update",t);const e=this.app.frame%2,i=this.sceneState[e];i.reset(),this.forEachElement(t=>i.pack(t));const s=i.compare(this.sceneState[1-e]),n=new Set([...s.added,...s.removed,...s.moved,...s.changed]);this.lockedRenderMode?(this.app.renderNextFrame=this.lockedRender,this.lockedRender=!1):this.app.renderNextFrame||(this.app.renderNextFrame=this.forceRender||n.size>0),this.forceRender=!1,ik.forEach(t=>{n.has(t)&&this.events.fire(`updated:${t}`)}),this.forEachElement(t=>t.onPostUpdate())}onPreRender(){this.canvasResize&&(this.canvas.width=this.canvasResize.width,this.canvas.height=this.canvasResize.height,this.canvasResize=null),this.targetSize.width=Math.ceil(this.app.graphicsDevice.width/this.config.camera.pixelScale),this.targetSize.height=Math.ceil(this.app.graphicsDevice.height/this.config.camera.pixelScale),this.forEachElement(t=>t.onPreRender()),this.events.fire("prerender",this.camera.entity.getWorldTransform()),this.config.debug.showBound&&(this.forEachElement(t=>{if(t.type===ek.splat){const e=t,i=e.localBound;this.app.drawWireAlignedBox(i.getMin(),i.getMax(),H.RED,!0,void 0,e.entity.getWorldTransform());const s=e.worldBound;this.app.drawWireAlignedBox(s.getMin(),s.getMax(),H.GREEN)}}),this.app.drawWireAlignedBox(this.bound.getMin(),this.bound.getMax(),H.BLUE))}onPostRender(){this.forEachElement(t=>t.onPostRender()),this.events.fire("postrender")}}const $k={bgClr:{r:0,g:0,b:0,a:1},selectedClr:{r:1,g:1,b:0,a:1},unselectedClr:{r:0,g:0,b:1,a:.5},lockedClr:{r:0,g:0,b:0,a:.05},camera:{pixelScale:1,multisample:!1,fov:65,exposure:1,toneMapping:"linear",debugRender:"",overlay:!0,highPrecision:!0},show:{grid:!0,bound:!0,shBands:3},controls:{dampingFactor:.2,minPolarAngle:0,maxPolarAngle:Math.PI,minZoom:1e-6,maxZoom:10,initialAzim:-45,initialElev:-10,initialZoom:1,orbitSensitivity:.3,zoomSensitivity:.4},debug:{showBound:!1}};class Kk{constructor(t){this.sources=t}resolve(t,e){const i=t=>{for(const i of e){if(!t.hasOwnProperty(i))return;t=t[i]}return t};for(const e of t){const t=i(e);if(void 0!==t)return t}}get(t){return this.resolve(this.sources,t.split(".").map(t=>t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(t,e)=>(e?"-":"")+t.toLowerCase())))??this.resolve(this.sources,t.split("."))}getBool(t){const e=this.get(t);return"string"==typeof e?"true"===e.toLowerCase():void 0===e?void 0:!!e}getNumber(t){const e=this.get(t);return"string"==typeof e?parseFloat(e):e}getVec(t){const e=this.get(t);return"string"==typeof e?e.split(","):void 0}getVec3(t){const e=this.getVec(t);if(e){const t=e.map(t=>parseFloat(t));if(1===e.length)return{x:t[0],y:t[0],z:t[0]};if(3===e.length)return{x:t[0],y:t[1],z:t[2]}}}getColor(t){const e=this.getVec(t);if(e){const t=e.map(t=>parseFloat(t));if(1===e.length)return{r:t[0],g:t[0],b:t[0],a:1};if(3===e.length)return{r:t[0],g:t[1],b:t[2],a:1};if(4===e.length)return{r:t[0],g:t[1],b:t[2],a:t[3]}}}}const Zk=t=>{const e=new Kk(t),i=(t,e)=>t.length===e.length&&t.every((t,i)=>t===e[i]),s=(t,n)=>{for(const r in t){const a=`${n}${n.length?".":""}${r}`,o=t[r];switch(typeof o){case"number":t[r]=e.getNumber(a)??o;break;case"boolean":t[r]=e.getBool(a)??o;break;case"string":t[r]=e.get(a)??o;break;case"object":{const n=Object.keys(o).sort();i(n,["a","b","g","r"])?t[r]=e.getColor(a)??o:i(n,["x","y","z"])?t[r]=e.getVec3(a)??o:s(o,a);break}default:s(o,a)}}};return s($k,""),$k};class Qk{constructor(t){this._selectedIndices=new Set,this._selectionMask=null,this._maskTotalSplats=0,this._maskDirty=!1,this._selectionTexture=null,this._graphicsDevice=null,this._cachedSplatData=null,this._cachedEntity=null,this._onEvent=null,this._highlightColor={r:1,g:.5,b:0,a:1},this._onEvent=t||null}setGraphicsDevice(t){this._graphicsDevice=t}initializeSelectionMask(t){t<=0||(this._selectionMask&&this._maskTotalSplats===t||(this._selectionMask=new Uint8Array(t),this._maskTotalSplats=t,this._maskDirty=!0),this._selectionMask.fill(0),this._selectedIndices.clear(),this._maskDirty=!0)}getSelectionMask(){return this._selectionMask}getSelectionMaskInfo(){if(!this._selectionMask)return null;const t=this._maskTotalSplats,e=Math.min(t,4096),i=Math.ceil(t/4096);return{mask:this._selectionMask,totalSplats:t,selectedCount:this._selectedIndices.size,isDirty:this._maskDirty,textureWidth:e,textureHeight:i}}syncMaskFromIndices(){if(this._selectionMask){this._selectionMask.fill(0);for(const t of this._selectedIndices)t>=0&&t<this._maskTotalSplats&&(this._selectionMask[t]=1);this._maskDirty=!0}}getOrCreateSelectionTexture(){if(!this._graphicsDevice||!this._selectionMask)return null;const t=this.getSelectionMaskInfo();if(!t)return null;if(!this._selectionTexture||this._maskDirty){this._selectionTexture&&this._selectionTexture.destroy();const e=t.textureWidth,i=Math.max(1,t.textureHeight),s=new Uint8Array(e*i);s.set(this._selectionMask.subarray(0,Math.min(this._selectionMask.length,e*i)));for(let t=0;t<s.length;t++)s[t]=s[t]?255:0;this._selectionTexture=new Gi(this._graphicsDevice,{name:"splat-selection-mask",width:e,height:i,format:Jt,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});this._selectionTexture.lock().set(s),this._selectionTexture.unlock(),this._maskDirty=!1}return this._selectionTexture}updateSelectionTexture(){if(!this._selectionTexture||!this._selectionMask||!this._maskDirty)return;const t=this._selectionTexture.width,e=this._selectionTexture.height,i=new Uint8Array(t*e),s=Math.min(this._selectionMask.length,t*e);for(let t=0;t<s;t++)i[t]=this._selectionMask[t]?255:0;this._selectionTexture.lock().set(i),this._selectionTexture.unlock(),this._maskDirty=!1}setHighlightColor(t,e,i,s=1){this._highlightColor={r:Math.max(0,Math.min(1,t)),g:Math.max(0,Math.min(1,e)),b:Math.max(0,Math.min(1,i)),a:Math.max(0,Math.min(1,s))},this._emitEvent("splat-highlight-color-changed",this._highlightColor)}getHighlightColor(){return{...this._highlightColor}}extractSplatData(t){const e={numSplats:0,x:null,y:null,z:null,hasPositions:!1};if(!t)return e;const i=t.gsplat;if(!i)return e;let s=null,n=null;i.instance?.resource?.gsplatData?(s=i.instance.resource.gsplatData,n=i.instance.resource):i.asset?.resource?.gsplatData?(s=i.asset.resource.gsplatData,n=i.asset.resource):i.instance?.gsplatData?s=i.instance.gsplatData:i.instance?.resource?.splatData&&(s=i.instance.resource.splatData,n=i.instance.resource),s?e.numSplats=s.numSplats||s.meta?.count||s.count||0:n?e.numSplats=n.numSplats||0:"number"==typeof i.numSplats?e.numSplats=i.numSplats:"number"==typeof i.splatCount&&(e.numSplats=i.splatCount);const r=(t,i)=>{e.x=new Float32Array(i),e.y=new Float32Array(i),e.z=new Float32Array(i);for(let s=0;s<i;s++)e.x[s]=t[3*s],e.y[s]=t[3*s+1],e.z[s]=t[3*s+2];e.numSplats=i,e.hasPositions=!0};if(s)if(s.x instanceof Float32Array)e.x=s.x,e.y=s.y,e.z=s.z,e.hasPositions=!0;else if(s.centers instanceof Float32Array){const t=s.centers;r(t,e.numSplats||t.length/3)}else if(s._centers instanceof Float32Array){const t=s._centers;r(t,e.numSplats||t.length/3)}else if(s.positions instanceof Float32Array){const t=s.positions;r(t,e.numSplats||t.length/3)}else if(s.means instanceof Float32Array){const t=s.means;r(t,e.numSplats||t.length/3)}if(!e.hasPositions&&n)if(n.centers instanceof Float32Array){const t=n.centers;r(t,e.numSplats||t.length/3)}else if(n._centers instanceof Float32Array){const t=n._centers;r(t,e.numSplats||t.length/3)}if(!e.hasPositions&&i.instance){const t=i.instance;if(t.centers instanceof Float32Array){const i=t.centers;r(i,e.numSplats||i.length/3)}else if("function"==typeof t.getCenters)try{const i=t.getCenters();if(i instanceof Float32Array){r(i,e.numSplats||i.length/3)}}catch(t){}}return this._cachedSplatData=e,this._cachedEntity=t,e.numSplats>0&&(!this._selectionMask||this._maskTotalSplats!==e.numSplats)&&this.initializeSelectionMask(e.numSplats),e}getDebugInfo(t){const e={hasGSplat:!1,hasPositionData:!1,positionDataFormat:null,centersLocation:null,numSplats:0};if(!t||!t.gsplat)return e;e.hasGSplat=!0;const i=t.gsplat,s=i.instance?.resource?.gsplatData||i.asset?.resource?.gsplatData||i.instance?.gsplatData||i.instance?.resource?.splatData||null,n=i.instance?.resource||i.asset?.resource||i.instance?.resource||null;return s&&(s.x instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.xyz",e.centersLocation="gsplatData.x/y/z",e.numSplats=s.x.length):s.centers instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.centers",e.centersLocation="gsplatData.centers",e.numSplats=s.centers.length/3):s._centers instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData._centers",e.centersLocation="gsplatData._centers",e.numSplats=s._centers.length/3):s.positions instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.positions",e.centersLocation="gsplatData.positions",e.numSplats=s.positions.length/3):s.means instanceof Float32Array&&(e.hasPositionData=!0,e.positionDataFormat="gsplatData.means",e.centersLocation="gsplatData.means",e.numSplats=s.means.length/3),!e.numSplats&&s.numSplats&&(e.numSplats=s.numSplats),!e.numSplats&&s.meta?.count&&(e.numSplats=s.meta.count)),!e.numSplats&&n?.numSplats&&(e.numSplats=n.numSplats),!e.hasPositionData&&i.instance?.centers instanceof Float32Array&&(e.hasPositionData=!0,e.positionDataFormat="instance.centers",e.centersLocation="instance.centers",e.numSplats=i.instance.centers.length/3),e}selectSplatsInBox(t,e,i=!1){let s=this._cachedSplatData;s&&this._cachedEntity===t||(s=this.extractSplatData(t)),this._selectionMask&&this._maskTotalSplats===s.numSplats||this.initializeSelectionMask(s.numSplats);const n={indices:new Uint32Array(0),count:0,totalSplats:s.numSplats,mask:this._selectionMask||new Uint8Array(0)};if(!(s.hasPositions&&s.x&&s.y&&s.z))return this._emitEvent("splat-selection-error",{message:"No position data available",code:"NO_POSITION_DATA"}),n;i||(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));const{x:r,y:a,z:o}=s,l=[];let h=null,c=!1;t&&t.getWorldTransform&&(h=t.getWorldTransform(),c=!0);for(let t=0;t<s.numSplats;t++){let i=r[t],s=a[t],n=o[t];if(c&&h){const e=h.data,l=r[t],c=a[t],d=o[t];i=e[0]*l+e[4]*c+e[8]*d+e[12],s=e[1]*l+e[5]*c+e[9]*d+e[13],n=e[2]*l+e[6]*c+e[10]*d+e[14]}i>=e.minX&&i<=e.maxX&&s>=e.minY&&s<=e.maxY&&n>=e.minZ&&n<=e.maxZ&&(this._selectedIndices.add(t),l.push(t),this._selectionMask&&(this._selectionMask[t]=1))}return this._maskDirty=!0,n.indices=new Uint32Array(this._selectedIndices),n.count=this._selectedIndices.size,n.mask=this._selectionMask||new Uint8Array(0),this._emitEvent("splat-selection-changed",{selectedCount:n.count,totalSplats:n.totalSplats,newlySelected:l.length,hasMask:!!this._selectionMask}),n}selectSplatsInSphere(t,e,i=!1){let s=this._cachedSplatData;s&&this._cachedEntity===t||(s=this.extractSplatData(t)),this._selectionMask&&this._maskTotalSplats===s.numSplats||this.initializeSelectionMask(s.numSplats);const n={indices:new Uint32Array(0),count:0,totalSplats:s.numSplats,mask:this._selectionMask||new Uint8Array(0)};if(!(s.hasPositions&&s.x&&s.y&&s.z))return this._emitEvent("splat-selection-error",{message:"No position data available",code:"NO_POSITION_DATA"}),n;i||(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));const{x:r,y:a,z:o}=s,l=[],h=e.radius*e.radius;let c=null,d=!1;t&&t.getWorldTransform&&(c=t.getWorldTransform(),d=!0);for(let t=0;t<s.numSplats;t++){let i=r[t],s=a[t],n=o[t];if(d&&c){const e=c.data,l=r[t],h=a[t],d=o[t];i=e[0]*l+e[4]*h+e[8]*d+e[12],s=e[1]*l+e[5]*h+e[9]*d+e[13],n=e[2]*l+e[6]*h+e[10]*d+e[14]}const u=i-e.cx,p=s-e.cy,f=n-e.cz;u*u+p*p+f*f<=h&&(this._selectedIndices.add(t),l.push(t),this._selectionMask&&(this._selectionMask[t]=1))}return this._maskDirty=!0,n.indices=new Uint32Array(this._selectedIndices),n.count=this._selectedIndices.size,n.mask=this._selectionMask||new Uint8Array(0),this._emitEvent("splat-selection-changed",{selectedCount:n.count,totalSplats:n.totalSplats,newlySelected:l.length,hasMask:!!this._selectionMask}),n}createBoxFromProperties(t,e){const i=e.x/2,s=e.y/2,n=e.z/2;return{minX:t.x-i,maxX:t.x+i,minY:t.y-s,maxY:t.y+s,minZ:t.z-n,maxZ:t.z+n}}getSelectedIndices(){return new Uint32Array(this._selectedIndices)}getSelectionCount(){return this._selectedIndices.size}clearSelection(){const t=this._selectedIndices.size;this._selectedIndices.clear(),this._selectionMask&&(this._selectionMask.fill(0),this._maskDirty=!0),this._emitEvent("splat-selection-cleared",{previousCount:t})}isSplatSelected(t){return this._selectedIndices.has(t)}addToSelection(t){for(const e of t)this._selectedIndices.add(e),this._selectionMask&&e>=0&&e<this._maskTotalSplats&&(this._selectionMask[e]=1);this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,added:t.length})}removeFromSelection(t){for(const e of t)this._selectedIndices.delete(e),this._selectionMask&&e>=0&&e<this._maskTotalSplats&&(this._selectionMask[e]=0);this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,removed:t.length})}invertSelection(t){this._selectionMask&&this._maskTotalSplats===t||this.initializeSelectionMask(t);const e=new Set;for(let i=0;i<t;i++)this._selectedIndices.has(i)?this._selectionMask&&(this._selectionMask[i]=0):(e.add(i),this._selectionMask&&(this._selectionMask[i]=1));this._selectedIndices=e,this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,inverted:!0})}selectByIndices(t,e=!0){e&&(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));for(const e of t)e>=0&&e<this._maskTotalSplats&&(this._selectedIndices.add(e),this._selectionMask&&(this._selectionMask[e]=1));this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,setDirectly:t.length})}selectAll(){if(!(this._maskTotalSplats<=0)){this._selectedIndices.clear();for(let t=0;t<this._maskTotalSplats;t++)this._selectedIndices.add(t);this._selectionMask&&this._selectionMask.fill(1),this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,selectedAll:!0})}}clearCache(){this._cachedSplatData=null,this._cachedEntity=null}isMaskDirty(){return this._maskDirty}markMaskClean(){this._maskDirty=!1}getMaskTotalSplats(){return this._maskTotalSplats}destroy(){this._selectedIndices.clear(),this._cachedSplatData=null,this._cachedEntity=null,this._onEvent=null,this._selectionMask=null,this._maskTotalSplats=0,this._maskDirty=!1,this._selectionTexture&&(this._selectionTexture.destroy(),this._selectionTexture=null),this._graphicsDevice=null}_emitEvent(t,e){this._onEvent&&this._onEvent(t,e)}}class Jk{constructor(t,e,i){this.device=null,this.events=null,this.scene=null,this.assetLoader=null,this.models=new Map,this.nextModelId=0,this.activeModelId=null,this.pendingGridEnabled=null,this.dataProcessor=null,this.navigationCube=null,this.navigationCubeConfig=null,this.emitEvent=null,this.viewerEventState={cameraMode:"centers",cameraOverlay:!0,cameraHighPrecision:!0,cameraBound:!0,cameraSplatSize:1,viewOutlineSelection:!1,viewBands:3},this.blobUrl=null,this.canvas=t,this.selectionMgr=new Qk,this.navigationCubeConfig=e||null,this.emitEvent=i||null}get currentSplat(){if(this.activeModelId){const t=this.models.get(this.activeModelId);if(t?.splat)return t.splat}const t=this.models.values().next().value;return t?.splat??null}getEntityTransform(t){const e=t.getLocalPosition(),i=t.getLocalRotation(),s=t.getLocalScale(),n=i.getEulerAngles(),r=t.getLocalTransform().data,a=[r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15]];return{position:{x:e.x,y:e.y,z:e.z},rotation:{x:n.x,y:n.y,z:n.z},scale:{x:s.x,y:s.y,z:s.z},matrix:a}}calculateBoundingBox(t){const e=new ut;if("function"==typeof t.getWorldTransform&&t.getWorldTransform(),"function"==typeof t._calculateHierarchyBounds)t._calculateHierarchyBounds(e);else if(t.gsplat?.bounds){const i=t.gsplat.bounds;e.center.set(i.center.x,i.center.y,i.center.z),e.halfExtents.set(i.halfExtents.x,i.halfExtents.y,i.halfExtents.z)}const i={x:e.center.x,y:e.center.y,z:e.center.z},s={x:e.halfExtents.x,y:e.halfExtents.y,z:e.halfExtents.z};return{center:i,halfExtents:s,min:{x:i.x-s.x,y:i.y-s.y,z:i.z-s.z},max:{x:i.x+s.x,y:i.y+s.y,z:i.z+s.z}}}getFileMeta(t){if("string"==typeof t){const e=(t.split("/").pop()||"").split("?")[0]||void 0,i=e?.split(".").pop()?.toLowerCase();return{fileSize:0,fileType:i||"unknown",fileName:e}}if(t instanceof File){const e=t.name.split(".").pop()?.toLowerCase();return{fileSize:t.size,fileType:e||"unknown",fileName:t.name}}return{fileSize:t.size,fileType:"blob"}}createPseudoAsset(t){return{name:t,type:"supersplat",loaded:!0,resource:null,unload:()=>{},destroy:()=>{}}}async init(){let t=await aa(this.canvas,{deviceTypes:["webgl2"],antialias:!1,depth:!1,stencil:!1,xrCompatible:!1,powerPreference:"high-performance"});if(t&&"object"==typeof t&&(t.graphicsDevice?t=t.graphicsDevice:t.device&&(t=t.device)),!t||!t.canvas)throw new Error("SupersplatAdapter: Failed to create graphics device");this.events=new xk;const e=Zk([{}]);if(this.scene=new jk(this.events,e,this.canvas,t),!this.scene?.app?.graphicsDevice)throw new Error("SupersplatAdapter: PlayCanvas app failed to initialize graphicsDevice");this.registerViewerEventDefaults(),this.assetLoader=new _k(this.scene.app,this.events,this.scene.app.graphicsDevice.maxAnisotropy),this.dataProcessor=new Sk(this.scene.app.graphicsDevice),this.scene.app.autoRender=!0,this.scene.start(),null!==this.pendingGridEnabled&&(this.scene.grid.visible=this.pendingGridEnabled,this.scene.forceRender=!0,this.pendingGridEnabled=null),this.setHighlightColor(1,.5,0,.8),this.initializeNavigationCube()}initializeNavigationCube(){if(this.navigationCubeConfig&&this.navigationCubeConfig.enabled&&this.scene&&this.scene.app&&this.scene.camera)try{this.navigationCube=new Pz(this.navigationCubeConfig);const t=this.createCameraAdapter();this.navigationCube.initialize(this.scene.app,this.scene.camera.entity,t,this.emitEvent||void 0),this.scene.app.on("update",this.updateNavigationCube.bind(this))}catch(t){this.navigationCube=null}}createCameraAdapter(){if(!this.scene||!this.scene.camera)throw new Error("SupersplatAdapter: Scene camera not available");const t=this.scene.camera;return{get pitch(){return t.elevation},get yaw(){return t.azim},get distance(){return t.distance},get target(){return t.focalPoint},updateCameraPosition:()=>{},setTargetPitch:(e,i)=>{const s=i?1:0;t.setAzimElev(t.azim,e,s)},setTargetYaw:(e,i)=>{const s=i?1:0;t.setAzimElev(e,t.elevation,s)},setAzimElev:(e,i,s)=>{const n=s?1:0;t.setAzimElev(e,i,n)}}}updateNavigationCube(t){this.navigationCube&&this.scene?.camera&&(this.navigationCube.update(t),this.navigationCube.syncWithCamera(this.scene.camera.elevation,this.scene.camera.azim))}async load(t){if(!this.scene||!this.assetLoader)throw new Error("SupersplatAdapter: init() must be called before load()");t instanceof Blob&&this._cleanupBlobUrl();const e=this.toAssetSource(t),i=performance.now();try{const s=await this.assetLoader.load(e);this.clear(),this.scene.add(s);const n="model_"+this.nextModelId++,r=this.getFileName(t);this.activeModelId=n;const a=this.getEntityTransform(s.entity),{fileSize:o,fileType:l,fileName:h}=this.getFileMeta(t),c=this.calculateBoundingBox(s.entity),d=this.getSplatCount(s),u=64*d,p=performance.now()-i,f={name:r,id:n,fileSize:o,fileType:l,splatCount:d,boundingBox:c,transform:a,memoryUsage:u,loadedAt:Date.now(),loadDuration:p};void 0!==h&&(f.fileName=h);const m=this.createPseudoAsset(r);return this.models.set(n,{id:n,name:r,splat:s,asset:m,visible:!0,transform:a,metadata:f}),this.scene.forceRender=!0,this.clearSelection(),this.emitEvent?.("model-added",{modelId:n,info:{id:n,name:r,entity:s.entity,asset:m,transform:a,metadata:f}}),{splat:s}}catch(t){throw t}}async addModel(t,e={}){if(!this.scene||!this.assetLoader)throw new Error("SupersplatAdapter: init() must be called before addModel()");const i=this.toAssetSource(t),s=performance.now();try{const n=await this.assetLoader.load(i);this.scene.add(n);const r="model_"+this.nextModelId++,a=e.name||this.getFileName(t);this.activeModelId=r;const o=this.getEntityTransform(n.entity),{fileSize:l,fileType:h,fileName:c}=this.getFileMeta(t),d=this.calculateBoundingBox(n.entity),u=this.getSplatCount(n),p=64*u,f=performance.now()-s,m={name:a,id:r,fileSize:l,fileType:h,splatCount:u,boundingBox:d,transform:o,memoryUsage:p,loadedAt:Date.now(),loadDuration:f};void 0!==c&&(m.fileName=c);const _=this.createPseudoAsset(a),g={id:r,name:a,splat:n,asset:_,visible:!1!==e.visible,transform:o,metadata:m};return this.models.set(r,g),g.visible||(n.visible=!1),this.scene.forceRender=!0,this.emitEvent?.("model-added",{modelId:r,info:{id:r,name:a,entity:n.entity,asset:_,transform:g.transform,metadata:g.metadata}}),{id:r,name:a,entity:n.entity,asset:_,transform:g.transform,metadata:g.metadata,visible:g.visible}}catch(t){throw t}}getSelectedIndices(){return this.selectionMgr.getSelectedIndices()}removeModel(t){const e=this.models.get(t);return!!e&&(this.scene&&(this.scene.remove(e.splat),e.splat.destroy()),this.models.delete(t),this.activeModelId===t&&(this.activeModelId=null),this.scene&&(this.scene.forceRender=!0),this.emitEvent?.("model-removed",{modelId:t}),!0)}getModels(){const t=[];return this.models.forEach(e=>{t.push({id:e.id,name:e.name,entity:e.splat.entity,asset:e.asset,transform:e.transform,metadata:e.metadata,visible:e.visible})}),t}getModelById(t){const e=this.models.get(t);return e?{id:e.id,name:e.name,entity:e.splat.entity,asset:e.asset,transform:e.transform,metadata:e.metadata,visible:e.visible}:null}updateModelTransform(t,e){const i=this.models.get(t);if(!i)throw new Error(`SupersplatAdapter.updateModelTransform: Model not found: ${t}`);i.transform=e,i.metadata.transform=e,this.scene&&(this.scene.forceRender=!0)}setGridEnabled(t){this.scene?(this.scene.grid.visible=t,this.scene.forceRender=!0):this.pendingGridEnabled=t}isGridEnabled(){return this.scene?.grid?.visible??this.pendingGridEnabled??!0}setModelVisible(t,e){const i=this.models.get(t);return!!i&&(i.visible=e,i.splat.visible=e,this.scene&&(this.scene.forceRender=!0),!0)}setModelsVisibleByName(t,e){this.models.forEach(i=>{i.name===t&&(i.visible=e,i.splat.visible=e)}),this.scene&&(this.scene.forceRender=!0)}getModelStats(t){const e=this.models.get(t);if(!e)throw new Error(`Model not found: ${t}`);return e.metadata}getAllModelStats(){const t={};return this.models.forEach((e,i)=>{t[i]=e.metadata}),t}getSceneStats(){let t=0,e=0,i=0,s=1/0,n=1/0,r=1/0,a=-1/0,o=-1/0,l=-1/0;this.models.forEach(h=>{t+=h.metadata.splatCount,e+=h.metadata.fileSize,i+=h.metadata.memoryUsage;const c=h.metadata.boundingBox;s=Math.min(s,c.min.x),n=Math.min(n,c.min.y),r=Math.min(r,c.min.z),a=Math.max(a,c.max.x),o=Math.max(o,c.max.y),l=Math.max(l,c.max.z)});const h=this.models.size>0&&isFinite(s)&&isFinite(a),c=h?{x:(s+a)/2,y:(n+o)/2,z:(r+l)/2}:{x:0,y:0,z:0},d=h?{x:(a-s)/2,y:(o-n)/2,z:(l-r)/2}:{x:0,y:0,z:0};return{modelCount:this.models.size,totalSplats:t,totalFileSize:e,totalMemoryUsage:i,bounds:{center:c,halfExtents:d}}}getFileName(t){return"string"==typeof t?t.split("/").pop()||"model.splat":t instanceof File?t.name:"model.splat"}getSplatCount(t){try{const e=t.splatData;if(e&&"number"==typeof e.numSplats)return e.numSplats}catch{}return 0}clear(){this._cleanupBlobUrl(),this.models.forEach(t=>{t.splat.destroy()}),this.models.clear(),this.scene?.clear(),this.clearSelection(),this.scene&&(this.scene.forceRender=!0)}focus(){this.scene&&(this.scene.forceRender=!0)}onCanvasResize(){this.navigationCube&&"function"==typeof this.navigationCube.onCanvasResize&&this.navigationCube.onCanvasResize()}destroy(){this.navigationCube&&("function"==typeof this.navigationCube.cleanup&&this.navigationCube.cleanup(),this.navigationCube=null)}setHighlightColor(t,e,i,s=.8){if(!this.events)return;const n=new H(t,e,i,s);this.events.fire("setSelectedClr",n)}setCameraFOV(t){this.scene&&("number"!=typeof t||isNaN(t)||t<1||t>179||(this.scene.camera.fov=t,this.scene.forceRender=!0))}getCameraFOV(){return this.scene?.camera?.fov??60}selectInBox(t,e=!1){const i=this.currentSplat;if(!i||!this.scene)return null;const s=this.selectionMgr.selectSplatsInBox(i.entity,t,e);return this.applySelectionToSplat(i,s?.indices),this.scene.forceRender=!0,s}selectInSphere(t,e=!1){const i=this.currentSplat;if(!i||!this.scene)return null;const s=this.selectionMgr.selectSplatsInSphere(i.entity,t,e);return this.applySelectionToSplat(i,s?.indices),this.scene.forceRender=!0,s}clearSelection(){const t=this.currentSplat;if(!t)return;const e=t.splatData.getProp("state");if(e){for(let t=0;t<e.length;t++)e[t]=-2&e[t];t.updateState(),this.scene&&(this.scene.forceRender=!0)}}applySelectionToSplat(t,e){if(!e)return;const i=t.splatData.getProp("state");if(i)if(0!==e.length){for(let t=0;t<i.length;t++)i[t]=-2&i[t];for(let t=0;t<e.length;t++){const s=e[t];s>=0&&s<i.length&&(i[s]=1|i[s])}t.updateState()}else this.clearSelection()}toAssetSource(t){if("string"==typeof t)return{url:t};if(t instanceof File)return{filename:t.name,contents:t};const e=URL.createObjectURL(t);return this.blobUrl=e,{filename:"local.splat",url:e,contents:t}}_cleanupBlobUrl(){if(this.blobUrl){try{URL.revokeObjectURL(this.blobUrl)}catch{}this.blobUrl=null}}getPlayCanvasContext(){return this.scene?{app:this.scene.app,root:this.scene.app.root,camera:this.scene.camera?.entity??null}:null}setCameraControlsEnabled(t){const e=this.scene?.camera?.controller;if(e)try{"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t)}catch(t){}}setCameraManualControl(t){const e=this.scene?.camera;if(e)try{"function"==typeof e.setManualControl?e.setManualControl(t):(e.manualControl=!!t,e.controller?.setEnabled?.(!t))}catch(t){}}syncOrbitFromCameraEntity(t=new K(0,0,0)){const e=this.scene?.camera,i=this.scene?.camera?.entity;if(e&&i)try{const s=i.getPosition?i.getPosition().clone():i.getLocalPosition().clone();"function"==typeof e.setPose&&e.setPose(s,t,0),this.scene&&(this.scene.forceRender=!0)}catch(t){}}registerViewerEventDefaults(){if(!this.events||!this.scene)return;const{config:t}=this.scene,e=this.viewerEventState,i=t.selectedClr??{r:1,g:.5,b:0,a:1},s=t.unselectedClr??{r:0,g:0,b:1,a:.5},n=t.lockedClr??{r:0,g:0,b:0,a:.05},r=t.bgClr??{r:0,g:0,b:0,a:1};e.cameraOverlay=t.camera?.overlay??e.cameraOverlay,e.cameraHighPrecision=t.camera?.highPrecision??e.cameraHighPrecision,e.cameraBound=t.show?.bound??e.cameraBound,e.viewBands=t.show?.shBands??e.viewBands,this.events.function("camera.mode",()=>e.cameraMode),this.events.on("camera.mode",t=>{e.cameraMode=t}),this.events.function("camera.overlay",()=>e.cameraOverlay),this.events.on("camera.overlay",t=>{e.cameraOverlay=!!t}),this.events.function("camera.highPrecision",()=>e.cameraHighPrecision),this.events.on("camera.highPrecision",t=>{e.cameraHighPrecision=!!t}),this.events.function("camera.bound",()=>e.cameraBound),this.events.on("camera.bound",t=>{e.cameraBound=!!t}),this.events.function("camera.splatSize",()=>e.cameraSplatSize),this.events.on("camera.splatSize",t=>{e.cameraSplatSize="number"==typeof t?t:e.cameraSplatSize}),this.events.function("view.outlineSelection",()=>e.viewOutlineSelection),this.events.on("view.outlineSelection",t=>{e.viewOutlineSelection=!!t}),this.events.function("view.bands",()=>e.viewBands),this.events.on("view.bands",t=>{e.viewBands="number"==typeof t?t:e.viewBands}),this.events.function("selectedClr",()=>i),this.events.function("unselectedClr",()=>s),this.events.function("lockedClr",()=>n),this.events.function("bgClr",()=>r),this.events.function("selection",()=>this.currentSplat)}}class tV{constructor(t){this._eventEmitter=t}applyTransformMatrix(t,e,i){const s=new rt;s.data.set(e);const{pos:n,rot:r,scale:a}=this.decomposeMatrix(s);t.setLocalPosition(n),t.setLocalRotation(r),t.setLocalScale(a);const o=this.getTransform(t);this.emitTransformEvent(i,o)}getTransformMatrix(t){const e=t.getLocalTransform().data;return[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]]}setPosition(t,e,i){t.setLocalPosition(e.x,e.y,e.z);const s=this.getTransform(t);this.emitTransformEvent(i,s)}setRotation(t,e,i){const s=this.eulerToQuat(e);t.setLocalRotation(s);const n=this.getTransform(t);this.emitTransformEvent(i,n)}setScale(t,e,i){t.setLocalScale(e.x,e.y,e.z);const s=this.getTransform(t);this.emitTransformEvent(i,s)}getTransform(t){const e=t.getLocalPosition(),i=t.getLocalRotation(),s=t.getLocalScale(),n=this.quatToEuler(i),r=this.getTransformMatrix(t);return{position:{x:e.x,y:e.y,z:e.z},rotation:n,scale:{x:s.x,y:s.y,z:s.z},matrix:r}}resetTransform(t,e){t.setLocalPosition(0,0,0),t.setLocalRotation(0,0,0,1),t.setLocalScale(1,1,1);const i=this.getTransform(t);this.emitTransformEvent(e,i)}decomposeMatrix(t){const e=new K,i=new at,s=new K;t.getTranslation(e);const n=t.data,r=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),a=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),o=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);s.set(r,a,o);const l=new rt;l.data[0]=n[0]/r,l.data[1]=n[1]/r,l.data[2]=n[2]/r,l.data[3]=0,l.data[4]=n[4]/a,l.data[5]=n[5]/a,l.data[6]=n[6]/a,l.data[7]=0,l.data[8]=n[8]/o,l.data[9]=n[9]/o,l.data[10]=n[10]/o,l.data[11]=0,l.data[12]=0,l.data[13]=0,l.data[14]=0,l.data[15]=1,l.getEulerAngles(i);const h=i;return i.setFromEulerAngles(h.x,h.y,h.z),{pos:e,rot:i,scale:s}}eulerToQuat(t){const e=new at;return e.setFromEulerAngles(t.x,t.y,t.z),e}quatToEuler(t){const e=new K;return t.getEulerAngles(e),{x:e.x,y:e.y,z:e.z}}emitTransformEvent(t,e){this._eventEmitter&&this._eventEmitter("model-transform-changed",{modelId:t,transform:e})}}var eV;!function(t){t.ORBIT="orbit",t.FLY="fly"}(eV||(eV={}));const iV={moveSpeed:5,fastSpeedMultiplier:3,slowSpeedMultiplier:.3,lookSensitivity:.2,invertY:!1,keyBindings:{forward:"KeyW",backward:"KeyS",left:"KeyA",right:"KeyD",up:"KeyE",down:"KeyQ",fastMove:"ShiftLeft",slowMove:"ControlLeft"},smoothing:.8,friction:.85,enableCollision:!1,minHeight:null,maxHeight:null};class SplatViewerCore{constructor(t={}){this.canvas=null,this.app=null,this.entities={camera:null,light:null,splat:null},this.enableStats=!1,this.autoFocus=!0,this.previewMode=!1,this.isLoading=!1,this.hasModel=!1,this.error=null,this._orbit=null,this._fly=null,this._cameraModeManager=null,this._cameraMode="orbit",this._statsHandler=null,this._asset=null,this._blobUrl=null,this._resizeObserver=null,this._resizeHandler=null,this.initialCameraPosition=null,this._navigationCubeConfig=null,this._modelManager=null,this._transformSystem=null,this._sceneConfigManager=null,this._skyboxEnabled=!1,this._skyboxLoadingPromise=null,this._eventListeners=new Map,this._splatCenterSize=null,this._sphericalHarmonicsBands=null,this._gridEnabled=!1,this._infiniteGrid=null,this._boxSelectionAPI=null,this._boxSelectionEnabled=!0,this._sphereSelectionAPI=null,this._sphereSelectionEnabled=!0,this._splatSelectionManager=null,this._splatHighlightShader=null,this._highlightEnabled=!0,this._splatHighlightOverlay=null,this._outlineEnabled=!1,this._supersplat=null,this._supersplatReady=null,this._supersplatBlobUrl=null,this._boundingBoxEnabled=!1,this._boundingBoxRenderHandler=null,this._selectedModelIdForBoundingBox=null,this.canvas=t.canvas||null,this.enableStats=t.enableStats||!1,this.autoFocus=!1!==t.autoFocus,this.previewMode=t.previewMode||!1,this.previewMode&&(this.autoFocus=!0),this._navigationCubeConfig=t.navigationCube||null,void 0!==t.onStatsUpdate&&(this._onStatsUpdate=t.onStatsUpdate),void 0!==t.onError&&(this._onError=t.onError),void 0!==t.onLoadingStart&&(this._onLoadingStart=t.onLoadingStart),void 0!==t.onLoaded&&(this._onLoaded=t.onLoaded)}async whenReady(){this._supersplatReady&&await this._supersplatReady}init(t){if(this.canvas=t||this.canvas,!this.canvas)throw new Error("SplatViewerCore.init: canvas is required");const e=(t,e)=>{this.emit({type:t,detail:e})};return this._supersplat=new Jk(this.canvas,this.previewMode?null:this._navigationCubeConfig,e),this._supersplatReady=this._supersplat.init(),this._supersplatReady?.then(()=>{this.previewMode&&this._supersplat&&this._supersplat.setCameraControlsEnabled?.(!1),this.previewMode||this._setupFlyCameraForSupersplat()}).catch(t=>{}),this._transformSystem=new tV(e),this._gridEnabled=!0,this._supersplatReady?.then(()=>{this._supersplat&&(this._gridEnabled=this._supersplat.isGridEnabled())}).catch(t=>{}),this.app=null,this}_setupFlyCameraForSupersplat(){if(!this._supersplat)return;const t=this._supersplat.getPlayCanvasContext?.();if(!t?.app||!t?.camera)return;this.app=t.app,this.entities.camera=t.camera;const e=this.entities.camera;if(e&&!e.script&&"function"==typeof e.addComponent)try{e.addComponent("script")}catch{}try{iD();const i={moveSpeed:iV.moveSpeed,fastSpeedMultiplier:iV.fastSpeedMultiplier,slowSpeedMultiplier:iV.slowSpeedMultiplier,lookSensitivity:iV.lookSensitivity,invertY:iV.invertY,keyBindings:iV.keyBindings,smoothing:iV.smoothing,friction:iV.friction,enableCollision:iV.enableCollision,minHeight:iV.minHeight,maxHeight:iV.maxHeight};if("function"==typeof e?.script?.create){const t=e.script.create("flyCamera",{attributes:i});this._fly=t,this._fly&&(this._fly.emitFlyEvent=(t,e)=>{this.emit({type:t,detail:e})},this._fly.deactivate?.())}else{const s=new eD(t.app,e,(t,e)=>this.emit({type:t,detail:e}),i);s.deactivate(),this._fly=s}this._cameraMode="orbit"}catch(t){}}_resolveModelEntityForId(t,e){if(this._supersplat){const i=this._supersplat.getModelById(t);if(!i||!i.entity)throw new Error(`${e}: Model with ID "${t}" not found (SuperSplat path)`);return i.entity}if(!this._modelManager)throw new Error(`${e}: ModelManager not initialized`);const i=this._modelManager.getModelById(t);if(!i)throw new Error(`${e}: Model with ID "${t}" not found`);return i.entity}async load(t,e={}){if(this._supersplat){await this._supersplatReady,this.clear(),this.isLoading=!0,this.error=null,this._onLoadingStart?.(),this.emit({type:"loading-start",detail:{source:"string"==typeof t?t:"file/blob"}});try{const e=await this._supersplat.load(t);return this.entities.splat=e.splat.entity,this.hasModel=!0,this.isLoading=!1,this._onLoaded?.({entity:this.entities.splat,asset:null}),this.emit({type:"loaded",detail:{entity:this.entities.splat,asset:null}}),{entity:this.entities.splat,asset:null}}catch(t){throw this.error="UNKNOWN_LOADER_ERROR",this._onError?.(this.error),this.emit({type:"error",detail:{message:this.error,code:"UNKNOWN_ERROR"}}),t}}if(!this.app)throw new Error("SplatViewerCore.load: call init() first");this.clear(),this.isLoading=!0,this.error=null,this._onLoadingStart?.(),this.emit({type:"loading-start",detail:{source:"string"==typeof t?t:"file/blob"}}),this.emit({type:"loading-progress",detail:{progress:.1}});try{let i;try{i=rD(t)}catch(t){}if(i&&aD(i.ext))try{this.emit({type:"loading-progress",detail:{progress:.3}});const s={applyRotation:!1,..."number"==typeof e.maxSplats&&{maxSplats:e.maxSplats}},n=await lD(this.app,t,s);if(this.entities.splat=n.entity,this._asset=n.asset,i.url&&i.blob)try{URL.revokeObjectURL(i.url)}catch(t){}return await new Promise(t=>{this.app.once("frameupdate",()=>{this._applySplatRenderingConfigToEntity(n.entity),this.autoFocus&&(this.focus(n.entity),setTimeout(()=>{this.debugInfo().boundsRadius||this.focus(n.entity)},100)),this.isLoading=!1,this.hasModel=!0,this._onLoaded?.(n),this.emit({type:"loaded",detail:{entity:n.entity,asset:n.asset}}),t(n)})})}catch(t){throw t instanceof nD?(this.error=t.code||"UNKNOWN_LOADER_ERROR",this._onError?.(this.error)):(this.error="UNKNOWN_LOADER_ERROR",this._onError?.(this.error)),this.isLoading=!1,this.emit({type:"error",detail:{message:this.error,code:t instanceof nD?t.code:"UNKNOWN_ERROR"}}),t}let s=null,n="gsplat";if("string"==typeof t)s=t,n=t.split("/").pop()||"gsplat";else{if(!(t instanceof Blob))throw new Error("Unsupported source type");s=URL.createObjectURL(t),this._blobUrl=s,n="local.ply"}try{this.emit({type:"loading-progress",detail:{progress:.5}});const t=new T_(n,"gsplat",{url:s}),e=new dC([t],this.app.assets);if(await new Promise(t=>e.load(()=>t())),this.emit({type:"loading-progress",detail:{progress:.8}}),!t||!1===t.loaded||!t.resource)throw new Error("GSplat asset failed to load");const i=new z_("splat");return i.addComponent("gsplat",{asset:t}),i.setLocalEulerAngles(270,0,0),this.app.root.addChild(i),this.entities.splat=i,this._asset=t,await new Promise(e=>{this.app.once("frameupdate",()=>{this._applySplatRenderingConfigToEntity(i),this.autoFocus&&(this.focus(i),setTimeout(()=>{this.debugInfo().boundsRadius||this.focus(i)},100)),this.isLoading=!1,this.hasModel=!0;const s={entity:i,asset:t};this._onLoaded?.(s),this.emit({type:"loaded",detail:{entity:s.entity,asset:s.asset}}),e(s)})})}catch(t){throw this.error="Failed to load splat",this._onError?.(this.error),this.isLoading=!1,this.emit({type:"error",detail:{message:this.error,code:"LOAD_FAILED"}}),t}}catch(t){throw this.isLoading=!1,t}}focus(t){if(this._supersplat)return void this._supersplat.focus();const e=t||this.entities.splat||this.app?.root;if(e&&this._orbit)try{const t=new ut;this.calcSceneBounds(t,e);const i=t.halfExtents.length();if(this._orbit&&void 0!==this._orbit.distance){const t=2.5*i;this._orbit.distance=t}const s=this.calcFocalPoint(t);if(this.initialCameraPosition)return this.initialCameraPosition=null,void(this._orbit&&void 0!==this._orbit.target&&(this._orbit.target=s));this._orbit&&void 0!==this._orbit.target&&(this._orbit.target=s),"function"==typeof this._orbit.focus&&this._orbit.focus(e)}catch(t){"function"==typeof this._orbit.focus&&this._orbit.focus(e)}}calcSceneBounds(t,e){if(e)if(t.center.set(0,0,0),t.halfExtents.set(0,0,0),e.getWorldTransform&&e.getWorldTransform(),e._calculateHierarchyBounds)e._calculateHierarchyBounds(t);else if(e.gsplat){const i=e.gsplat;if(i.bounds)t.copy(i.bounds);else if(i.boundingBox)t.copy(i.boundingBox);else if(i.instance&&i.instance.meshInstance){const e=i.instance.meshInstance;e.aabb&&t.copy(e.aabb)}else if(i.asset&&i.asset.resource){const e=i.asset.resource;e&&e.aabb&&t.copy(e.aabb)}}}calcFocalPoint(t){return t.center.clone()}async addModel(t,e={}){if(this._supersplat)return await this._supersplatReady,await this._supersplat.addModel(t,e);if(!this._modelManager)throw new Error("SplatViewerCore.addModel: ModelManager not initialized");const i=await this._modelManager.addModel(t,e);return i?.entity&&this._applySplatRenderingConfigToEntity(i.entity),i}removeModel(t){if(this._supersplat)this._supersplat.removeModel(t);else{if(!this._modelManager)throw new Error("SplatViewerCore.removeModel: ModelManager not initialized");this._modelManager.removeModel(t)}}getModels(){return this._supersplat?this._supersplat.getModels():this._modelManager?this._modelManager.getModels():[]}getModelStats(t){if(this._supersplat)return this._supersplat.getModelStats(t);if(!this._modelManager)throw new Error("SplatViewerCore.getModelStats: ModelManager not initialized");return this._modelManager.getModelStats(t)}getAllModelStats(){return this._supersplat?this._supersplat.getAllModelStats():this._modelManager?this._modelManager.getAllModelStats():{}}getSceneStats(){return this._supersplat?this._supersplat.getSceneStats():this._modelManager?this._modelManager.getSceneStats():{modelCount:0,totalSplats:0,totalFileSize:0,totalMemoryUsage:0,bounds:{center:{x:0,y:0,z:0},halfExtents:{x:0,y:0,z:0}}}}setFlyCameraSpeed(t){t<=0||!isFinite(t)||this.setFlyCameraConfig({moveSpeed:t})}getFlyCameraSpeed(){const t=this.getFlyCameraConfig();return t?t.moveSpeed:null}setModelVisible(t,e){if(this._supersplat)this._supersplat.setModelVisible(t,e);else{if(!this._modelManager)throw new Error("SplatViewerCore.setModelVisible: ModelManager not initialized");this._modelManager.setModelVisible(t,e)}}setModelsVisibleByName(t,e){if(this._supersplat)this._supersplat.setModelsVisibleByName(t,e);else{if(!this._modelManager)throw new Error("SplatViewerCore.setModelsVisibleByName: ModelManager not initialized");this._modelManager.setModelsVisibleByName(t,e)}}setSplatCenterSize(t){if(!isFinite(t)||t<=0)return;const e=this._splatCenterSize;this._splatCenterSize=t,this._forEachSplatEntity(t=>{this._applySplatRenderingConfigToEntity(t)}),this.emit({type:"splat-center-size-changed",detail:{size:t,previousSize:e??t}})}getSplatCenterSize(){return this._splatCenterSize}setSphericalHarmonicsBands(t){if(!isFinite(t))return;const e=Math.max(0,Math.min(3,Math.round(t))),i=this._sphericalHarmonicsBands;this._sphericalHarmonicsBands=e,this._forEachSplatEntity(t=>{this._applySplatRenderingConfigToEntity(t)}),this.emit({type:"spherical-harmonics-bands-changed",detail:{bands:e,previousBands:i??e}})}getSphericalHarmonicsBands(){return this._sphericalHarmonicsBands}setGridEnabled(t){if(this._supersplat)return this._supersplat.setGridEnabled(t),void(this._gridEnabled=t);if(!this.app)throw new Error("SplatViewerCore.setGridEnabled: PlayCanvas app not initialized. Call init() first.");this._gridEnabled=t,t&&!this._infiniteGrid&&this._setupInfiniteGrid(),this._infiniteGrid&&(this._infiniteGrid.visible=t)}isGridEnabled(){return this._supersplat?this._supersplat.isGridEnabled():this._gridEnabled}_setupInfiniteGrid(){this.app&&!this._infiniteGrid&&(this._infiniteGrid=new sD(this.app,()=>this.entities.camera||null))}_setupBoxSelection(){if(!this.app&&this._supersplat){const t=this._supersplat.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)}this.app&&!this._boxSelectionAPI&&(this._boxSelectionAPI=new Nz,this._boxSelectionAPI.initialize(this.app,this.app.root,this.entities.camera||null,(t,e)=>this.emit({type:t,detail:e})),this._boxSelectionAPI.setCameraControlCallback(t=>{if(this._supersplat?.setCameraControlsEnabled?.(t),this._orbit){const e=this._orbit;"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t),void 0!==e._inputEnabled&&(e._inputEnabled=t)}}),this.app.on("prerender",()=>{this._boxSelectionAPI?.update()}))}createSelectionBox(t){return this._boxSelectionAPI||(this._setupBoxSelection(),this._boxSelectionAPI)?this._boxSelectionAPI.createBox(t):null}removeSelectionBox(t){return!!this._boxSelectionAPI&&this._boxSelectionAPI.removeBox(t)}clearSelectionBoxes(){this._boxSelectionAPI?.clear()}setBoxSize(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxSize(t,e,i,s)}getBoxSize(t){return this._boxSelectionAPI?.getBoxSize(t)??null}setBoxPosition(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxPosition(t,e,i,s)}getBoxPosition(t){return this._boxSelectionAPI?.getBoxPosition(t)??null}setBoxColor(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxColor(t,e,i,s)}showBox(t,e){return!!this._boxSelectionAPI&&this._boxSelectionAPI.showBox(t,e)}getAllSelectionBoxes(){return this._boxSelectionAPI?.getAllBoxes()??[]}getSelectedBoxId(){return this._boxSelectionAPI?.getSelectedBoxId()??null}selectBox(t){return!!this._boxSelectionAPI&&this._boxSelectionAPI.selectBox(t)}setBoxSelectionEnabled(t){this._boxSelectionEnabled=t,t&&!this._boxSelectionAPI&&this.app&&this._setupBoxSelection(),this._boxSelectionAPI&&this._boxSelectionAPI.setInteractionEnabled(t)}isBoxSelectionEnabled(){return this._boxSelectionEnabled}_setupSphereSelection(){if(!this.app&&this._supersplat){const t=this._supersplat.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)}this.app&&!this._sphereSelectionAPI&&(this._sphereSelectionAPI=new Uz,this._sphereSelectionAPI.initialize(this.app,this.app.root,this.entities.camera||null,(t,e)=>this.emit({type:t,detail:e})),this._sphereSelectionAPI.setCameraControlCallback(t=>{if(this._supersplat?.setCameraControlsEnabled?.(t),this._orbit){const e=this._orbit;"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t),void 0!==e._inputEnabled&&(e._inputEnabled=t)}}),this.app.on("prerender",()=>{this._sphereSelectionAPI?.update()}))}createSelectionSphere(t){return this._sphereSelectionAPI||(this._setupSphereSelection(),this._sphereSelectionAPI)?this._sphereSelectionAPI.createSphere(t):null}removeSelectionSphere(t){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.removeSphere(t)}clearSelectionSpheres(){this._sphereSelectionAPI?.clear()}setSphereRadius(t,e){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSphereRadius(t,e)}getSphereRadius(t){return this._sphereSelectionAPI?.getSphereRadius(t)??null}setSpherePosition(t,e,i,s){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSpherePosition(t,e,i,s)}getSpherePosition(t){return this._sphereSelectionAPI?.getSpherePosition(t)??null}setSphereColor(t,e,i,s){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSphereColor(t,e,i,s)}showSphere(t,e){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.showSphere(t,e)}getAllSelectionSpheres(){return this._sphereSelectionAPI?.getAllSpheres()??[]}getSelectedSphereId(){return this._sphereSelectionAPI?.getSelectedSphereId()??null}setSphereSelectionEnabled(t){this._sphereSelectionEnabled=t,t&&!this._sphereSelectionAPI&&this.app&&this._setupSphereSelection(),this._sphereSelectionAPI&&this._sphereSelectionAPI.setInteractionEnabled(t)}isSphereSelectionEnabled(){return this._sphereSelectionEnabled}selectSphere(t){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.selectSphere(t)}getSplatDataDebugInfo(t){if(!this._splatSelectionManager)return{error:"SplatSelectionManager not initialized"};let e=this.entities.splat;if(t&&this._modelManager){const i=this._modelManager.getModelById(t);i?.entity&&(e=i.entity)}return this._splatSelectionManager.getDebugInfo(e)}extractSplatData(t){if(!this._splatSelectionManager)return null;let e=this.entities.splat;if(t&&this._modelManager){const i=this._modelManager.getModelById(t);i?.entity&&(e=i.entity)}return e?this._splatSelectionManager.extractSplatData(e):null}selectSplatsInBox(t,e,i=!1){if(this._supersplat){const e=this._boxSelectionAPI?.getBoxProperties(t);if(!e)return null;const s={minX:e.position.x-e.size.x/2,maxX:e.position.x+e.size.x/2,minY:e.position.y-e.size.y/2,maxY:e.position.y+e.size.y/2,minZ:e.position.z-e.size.z/2,maxZ:e.position.z+e.size.z/2};return this._supersplat.selectInBox(s,i)}if(!this._splatSelectionManager||!this._boxSelectionAPI)return null;const s=this._boxSelectionAPI.getBoxProperties(t);if(!s)return null;let n=this.entities.splat;if(e&&this._modelManager){const t=this._modelManager.getModelById(e);t?.entity&&(n=t.entity)}if(!n)return null;const r={minX:s.position.x-s.size.x/2,maxX:s.position.x+s.size.x/2,minY:s.position.y-s.size.y/2,maxY:s.position.y+s.size.y/2,minZ:s.position.z-s.size.z/2,maxZ:s.position.z+s.size.z/2},a=this._splatSelectionManager.selectSplatsInBox(n,r,i);return this._updateHighlightOverlay(n,a),a}selectSplatsInSphere(t,e,i,s=!1){if(this._supersplat){const i={cx:t.x,cy:t.y,cz:t.z,radius:e};return this._supersplat.selectInSphere(i,s)}if(!this._splatSelectionManager)return null;let n=this.entities.splat;if(i&&this._modelManager){const t=this._modelManager.getModelById(i);t?.entity&&(n=t.entity)}if(!n)return null;const r={cx:t.x,cy:t.y,cz:t.z,radius:e},a=this._splatSelectionManager.selectSplatsInSphere(n,r,s);return this._updateHighlightOverlay(n,a),a}selectSplatsInSphereById(t,e,i=!1){if(this._supersplat){const e=this._sphereSelectionAPI?.getSphereProperties(t);if(!e)return null;const s={cx:e.position.x,cy:e.position.y,cz:e.position.z,radius:e.radius};return this._supersplat.selectInSphere(s,i)}if(!this._splatSelectionManager)return null;const s=this._sphereSelectionAPI?.getSphereProperties(t);if(!s)return null;let n=this.entities.splat;if(e&&this._modelManager){const t=this._modelManager.getModelById(e);t?.entity&&(n=t.entity)}if(!n)return null;const r={cx:s.position.x,cy:s.position.y,cz:s.position.z,radius:s.radius},a=this._splatSelectionManager.selectSplatsInSphere(n,r,i);return this._updateHighlightOverlay(n,a),a}clearSplatSelection(){this._supersplat?this._supersplat.clearSelection():(this._splatSelectionManager?.clearSelection(),this._splatHighlightOverlay?.clear())}getSelectedSplats(){return this._supersplat?this._supersplat.getSelectedIndices():this._splatSelectionManager?.getSelectedIndices()??new Uint32Array(0)}setHighlightEnabled(t){this._highlightEnabled=t,this._supersplat||(this._splatHighlightOverlay&&(this._splatHighlightOverlay.setEnabled(t),t||this._splatHighlightOverlay.clear()),this._splatHighlightShader&&this._splatHighlightShader.setEnabled(t))}isHighlightEnabled(){return this._highlightEnabled}setHighlightColor(t,e,i,s=.7){this._supersplat?this._supersplat.setHighlightColor(t,e,i,s):(this._splatHighlightShader?.setHighlightColor(t,e,i,s),this._splatHighlightOverlay?.setColor(t,e,i,s))}getHighlightColor(){return this._splatHighlightShader?this._splatHighlightShader.getConfig().color:null}setHighlightMode(t){this._splatHighlightShader?.setHighlightMode(t)}getHighlightMode(){return this._splatHighlightShader?this._splatHighlightShader.getConfig().mode:null}setHighlightOverlayStyle(t){this._splatHighlightOverlay?.setStyle(t)}setHighlightOverlaySize(t){this._splatHighlightOverlay?.setPointSize(t)}setOutlineEnabled(t){this._outlineEnabled=t,this._splatHighlightShader?.setEnabled(t)}isOutlineEnabled(){return this._outlineEnabled}_updateHighlightOverlay(t,e){if(!this._splatHighlightOverlay||!this._splatSelectionManager||!e)return;const i=this._splatSelectionManager.extractSplatData(t);i.hasPositions&&i.x&&i.y&&i.z?this._splatHighlightOverlay.updateSelectionFromSplatData(i.x,i.y,i.z,Array.from(e.indices),t.getWorldTransform?t.getWorldTransform():void 0):this._splatHighlightOverlay.clear()}setBoundingBoxEnabled(t){if(this._boundingBoxEnabled=t,t){if(!this.app&&this._supersplat){const t=()=>{if(this.app)return;const t=this._supersplat?.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)};if(t(),!this.app&&this._supersplatReady)return void this._supersplatReady.then(()=>{t(),this._boundingBoxEnabled&&this.app&&!this._boundingBoxRenderHandler&&this._setupBoundingBoxRenderer()}).catch(t=>{})}if(!this.app)throw new Error("SplatViewerCore.setBoundingBoxEnabled: PlayCanvas app not initialized. Call init() first.");this._boundingBoxRenderHandler||this._setupBoundingBoxRenderer()}}isBoundingBoxEnabled(){return this._boundingBoxEnabled}setBoundingBoxSelection(t){t!==this._selectedModelIdForBoundingBox&&(this._selectedModelIdForBoundingBox=t)}getBoundingBoxSelection(){return this._selectedModelIdForBoundingBox}_setupBoundingBoxRenderer(){if(!this.app||this._boundingBoxRenderHandler)return;const t=this.app,e=new ut,i=new H(1,1,1);this._boundingBoxRenderHandler=()=>{if(!this._boundingBoxEnabled)return;let s=null;if(this._modelManager&&this._selectedModelIdForBoundingBox){const t=this._modelManager.getModelById(this._selectedModelIdForBoundingBox);t&&t.entity&&(s=t.entity)}if(!s&&this.entities.splat&&(s=this.entities.splat),!s)return;this.calcSceneBounds(e,s);const n=e.halfExtents;if(!n||0===n.length())return;const r=e.center,a=r.x-n.x,o=r.x+n.x,l=r.y-n.y,h=r.y+n.y,c=r.z-n.z,d=r.z+n.z,u=new K(a,l,c),p=new K(a,l,d),f=new K(a,h,c),m=new K(a,h,d),_=new K(o,l,c),g=new K(o,l,d),v=new K(o,h,c),y=new K(o,h,d),S=!0;t.drawLine(u,_,i,S),t.drawLine(_,g,i,S),t.drawLine(g,p,i,S),t.drawLine(p,u,i,S),t.drawLine(f,v,i,S),t.drawLine(v,y,i,S),t.drawLine(y,m,i,S),t.drawLine(m,f,i,S),t.drawLine(u,f,i,S),t.drawLine(_,v,i,S),t.drawLine(g,y,i,S),t.drawLine(p,m,i,S)},t.on("update",this._boundingBoxRenderHandler)}_applySplatRenderingConfigToEntity(t){const e=t.gsplat;if(e){if(null!=this._splatCenterSize){const t=this._splatCenterSize;if("centerSize"in e&&(e.centerSize=t),"centersSize"in e&&(e.centersSize=t),"pointSize"in e&&(e.pointSize=t),e.settings&&("centerSize"in e.settings&&(e.settings.centerSize=t),"centersSize"in e.settings&&(e.settings.centersSize=t),"pointSize"in e.settings&&(e.settings.pointSize=t)),e.instance&&("centerSize"in e.instance&&(e.instance.centerSize=t),"centersSize"in e.instance&&(e.instance.centersSize=t),"pointSize"in e.instance&&(e.instance.pointSize=t),e.instance.renderOptions)){const i=e.instance.renderOptions;"centerSize"in i&&(i.centerSize=t),"centersSize"in i&&(i.centersSize=t),"pointSize"in i&&(i.pointSize=t)}}if(null!=this._sphericalHarmonicsBands){const t=this._sphericalHarmonicsBands;"shBands"in e&&(e.shBands=t),"shBandCount"in e&&(e.shBandCount=t),"sphericalHarmonicsBands"in e&&(e.sphericalHarmonicsBands=t),e.settings&&("shBands"in e.settings&&(e.settings.shBands=t),"shBandCount"in e.settings&&(e.settings.shBandCount=t),"sphericalHarmonicsBands"in e.settings&&(e.settings.sphericalHarmonicsBands=t)),e.instance&&("shBands"in e.instance&&(e.instance.shBands=t),"shBandCount"in e.instance&&(e.instance.shBandCount=t),"sphericalHarmonicsBands"in e.instance&&(e.instance.sphericalHarmonicsBands=t))}this._splatHighlightShader&&this._splatHighlightShader.applyUniforms(e)}}_forEachSplatEntity(t){if(this.entities.splat&&t(this.entities.splat),this._supersplat){const e=this._supersplat.getModels();for(const i of e)i.entity&&t(i.entity)}if(this._modelManager){const e=this._modelManager.getModels();for(const i of e)i.entity&&t(i.entity)}}applyTransformMatrix(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.applyTransformMatrix: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.applyTransformMatrix");this._transformSystem.applyTransformMatrix(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelPosition(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelPosition: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelPosition");this._transformSystem.setPosition(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelRotation(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelRotation: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelRotation");this._transformSystem.setRotation(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelScale(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelScale: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelScale");this._transformSystem.setScale(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}getModelTransform(t){if(!this._transformSystem)throw new Error("SplatViewerCore.getModelTransform: TransformSystem not initialized");const e=this._resolveModelEntityForId(t,"SplatViewerCore.getModelTransform");return this._transformSystem.getTransform(e)}resetModelTransform(t){if(!this._transformSystem)throw new Error("SplatViewerCore.resetModelTransform: TransformSystem not initialized");const e=this._resolveModelEntityForId(t,"SplatViewerCore.resetModelTransform");this._transformSystem.resetTransform(e,t);const i=this._transformSystem.getTransform(e);this._supersplat?this._supersplat.updateModelTransform(t,i):this._modelManager&&this._modelManager.updateModelTransform(t,i)}clear(){if(this._supersplat)this._supersplat.clear(),this.entities.splat=null;else{if(this._modelManager&&this._modelManager.clear(),this.entities.splat&&(this.entities.splat.destroy(),this.entities.splat=null),this._asset){this._asset.unload();try{this.app?.assets?.remove?.(this._asset)}catch{}const t=this._asset;"function"==typeof t.destroy&&t.destroy(),this._asset=null}this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}this.hasModel=!1,this.error=null,this._selectedModelIdForBoundingBox=null,this._boxSelectionAPI?.clear(),this._sphereSelectionAPI?.clear(),this._splatSelectionManager?.clearSelection(),this._splatSelectionManager?.clearCache(),this._splatHighlightOverlay?.clear()}destroy(){if(this.app){if(this.clear(),this._infiniteGrid){try{this._infiniteGrid.destroy()}catch{}this._infiniteGrid=null}if(this._boundingBoxRenderHandler){try{this.app.off("update",this._boundingBoxRenderHandler)}catch{}this._boundingBoxRenderHandler=null}this._modelManager=null,this._boxSelectionAPI?.clear(),this._boxSelectionAPI=null,this._sphereSelectionAPI?.clear(),this._sphereSelectionAPI=null,this._splatSelectionManager?.destroy(),this._splatSelectionManager=null,this._splatHighlightOverlay?.destroy(),this._splatHighlightOverlay=null,this._splatHighlightShader?.isShaderApplied()&&this._splatHighlightShader.restoreOriginalShader(),this._splatHighlightShader=null,this._statsHandler&&(this.app.off("frameend",this._statsHandler),this._statsHandler=null),this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null);try{this.entities.camera&&(this.entities.camera.destroy(),this.entities.camera=null)}catch(t){}try{this.entities.light&&(this.entities.light.destroy(),this.entities.light=null)}catch(t){}try{this.app.destroy()}catch(t){throw t}this.app=null,this._orbit=null}}debugInfo(){const t=this._asset,e=this.entities.splat,i=!!e?.gsplat;let s=null,n=null;if(e){const t=e.gsplat;if(t){const e=t.bounds||t.boundingBox||null;e?.halfExtents?(s=Math.max(1,e.halfExtents.length()),n="gsplat.bounds"):"number"==typeof t.radius&&(s=Math.max(1,t.radius),n="gsplat.radius")}if(null==s&&e._calculateHierarchyBounds){const t=new ut;e.getWorldTransform(),e._calculateHierarchyBounds(t),t.halfExtents.length()>0&&(s=Math.max(1,t.halfExtents.length()),n="hierarchy")}}return{assetName:t?.name||null,assetUrl:t?.file?.url||t?.url||null,hasEntity:!!e,hasGsplatComponent:i,cameraDistance:this._orbit?.distance??null,boundsRadius:s,boundsSource:n,cameraTarget:this._orbit?.target?this._orbit.target.toString():null}}on(t,e){this._eventListeners.has(t)||this._eventListeners.set(t,new Set),this._eventListeners.get(t).add(e)}off(t,e){const i=this._eventListeners.get(t);i&&(i.delete(e),0===i.size&&this._eventListeners.delete(t))}emit(t){const e=this._eventListeners.get(t.type);e&&e.forEach(e=>{try{e(t)}catch(t){}})}setCameraPosition(t){this.entities.camera&&(this.entities.camera.setPosition(t),this.emit({type:"camera-change",detail:{position:t,target:this._orbit?.target||{x:0,y:0,z:0}}}))}setCameraTarget(t){this._orbit&&(this._orbit.target=t,this._orbit.updateCameraPosition?.(),this.emit({type:"camera-change",detail:{position:this.entities.camera?.getPosition?.()||{x:0,y:0,z:0},target:t}}))}resetCamera(){this._orbit&&(this._orbit.target={x:0,y:0,z:0},this._orbit.distance=10,this._orbit.pitch=-15,this._orbit.yaw=45,this._orbit.updateCameraPosition?.(),this.emit({type:"camera-change",detail:{position:this.entities.camera?.getPosition?.()||{x:0,y:0,z:0},target:{x:0,y:0,z:0}}}))}async setSkyboxEnabled(t){const e=this.app??this._supersplat?.getPlayCanvasContext?.()?.app;if(!e)return void(this._skyboxEnabled=!!t);const i=e.scene;if(t===this._skyboxEnabled&&i?.skybox)return;if(!t)return this._skyboxEnabled=!1,void(i&&"skybox"in i&&(i.skybox=null));if(this._skyboxLoadingPromise)return await this._skyboxLoadingPromise,void(this._skyboxEnabled=!0);const s=this._loadDefaultSkyboxCubemap(e);this._skyboxLoadingPromise=s;try{await s,this._skyboxEnabled=!0}catch(t){throw this._skyboxEnabled=!1,t}finally{this._skyboxLoadingPromise===s&&(this._skyboxLoadingPromise=null)}}isSkyboxEnabled(){return this._skyboxEnabled}async _loadDefaultSkyboxCubemap(t){const e=t??this.app??null;if(!e)return;const i=e.scene;if(i&&i.skybox)return;const s="/assets/skybox",n=["skybox_px.jpg","skybox_nx.jpg","skybox_py.jpg","skybox_ny.jpg","skybox_pz.jpg","skybox_nz.jpg"].map(t=>`${s}/${t}`).map((t,i)=>{const s=new T_(`skybox-face-${i}`,"texture",{url:t});try{e.assets?.add?.(s)}catch{}return s}),r=new dC(n,e.assets);if(await new Promise((t,e)=>{r.load(i=>{i?e(new Error(`SplatViewerCore: Failed to load skybox textures from ${s}: ${i}`)):t()})}),!n[0]||!n[0].resource)throw new Error("SplatViewerCore: Skybox textures loaded but no texture resource was found.");n[0].resource;const a=Gi;if(!a)return;const o=n.map((t,e)=>{if(!t||!t.resource)throw new Error(`SplatViewerCore: Missing skybox face texture at index ${e}.`);return t.resource}),l=o[0],h=Array.isArray(l._levels)&&l._levels.length>0?l._levels.length:0;if(0===h)return;const c=[];for(let t=0;t<h;t++)c.push(o.map(e=>e._levels[t]));const d=6===l.format?7:l.format,u=new a(e.graphicsDevice,{name:"splat-viewer-skybox",cubemap:!0,type:l.type,width:l.width,height:l.height,format:d,mipmaps:!0,levels:c,minFilter:l.minFilter,magFilter:l.magFilter,anisotropy:"number"==typeof l.anisotropy?l.anisotropy:1,addressU:1,addressV:1});i&&(i.skybox=u)}setCameraMode(t){if(!this.previewMode){if(this._supersplat){const e=this._cameraMode;if(t===e)return;if(!this._fly)try{this._setupFlyCameraForSupersplat()}catch{}if("fly"===t){if(this._supersplat.setCameraControlsEnabled(!1),this._supersplat.setCameraManualControl(!0),this._fly)if("function"==typeof this._fly.syncFromEntity)this._fly.syncFromEntity();else try{const t=this.entities.camera?.getPosition?.();if(t){const e=t.clone?t.clone():new K(t.x||0,t.y||0,t.z||0);this.entities.camera?.setPosition?.(e)}const e=this.entities.camera?.getEulerAngles?.();e&&(this._fly._pitch=e.x||0,this._fly._yaw=e.y||0)}catch{}this._fly?.activate?.(),this._cameraMode="fly"}else this._fly?.deactivate?.(),this._supersplat.setCameraManualControl(!1),this._supersplat.setCameraControlsEnabled(!0),this._supersplat.syncOrbitFromCameraEntity?.(new K(0,0,0)),this._cameraMode="orbit";return void this.emit({type:"camera-mode-changed",detail:{mode:this._cameraMode,previousMode:e}})}this._cameraModeManager&&this._cameraModeManager.setMode(t)}}setCameraFOV(t){if(this._supersplat?.setCameraFOV){const e=this._supersplat.getCameraFOV?.()??t;return this._supersplat.setCameraFOV(t),void this.emit({type:"camera-fov-changed",detail:{fov:t,previousFov:e}})}this._sceneConfigManager&&this._sceneConfigManager.setCameraFOV(t)}getCameraFOV(){return this._supersplat?.getCameraFOV?this._supersplat.getCameraFOV():this._sceneConfigManager?this._sceneConfigManager.getCameraFOV():this.entities.camera?.camera?.fov??60}async animateCameraFOV(t,e){if(this._supersplat?.setCameraFOV&&this._supersplat?.getCameraFOV){const i=this._supersplat.getCameraFOV(),s=performance.now(),n=Math.max(0,Number(e)||0),r=t=>Math.max(1,Math.min(179,t)),a=r(t);return 0===n?(this._supersplat.setCameraFOV(a),void this.emit({type:"camera-fov-changed",detail:{fov:a,previousFov:i}})):void await new Promise(t=>{const e=()=>{const o=performance.now(),l=Math.min(1,(o-s)/n),h=i+(a-i)*l;if(this._supersplat.setCameraFOV(r(h)),l>=1)return this.emit({type:"camera-fov-changed",detail:{fov:a,previousFov:i}}),void t();requestAnimationFrame(e)};requestAnimationFrame(e)})}this._sceneConfigManager&&await this._sceneConfigManager.animateCameraFOV(t,e)}setBackgroundColor(t){this._sceneConfigManager&&this._sceneConfigManager.setBackgroundColor(t)}getBackgroundColor(){return this._sceneConfigManager?this._sceneConfigManager.getBackgroundColor():{r:26,g:26,b:26,a:1}}async animateBackgroundColor(t,e){this._sceneConfigManager&&await this._sceneConfigManager.animateBackgroundColor(t,e)}getCameraMode(){return this._supersplat?this._cameraMode:this._cameraModeManager?.getMode()||"orbit"}setFlyCameraConfig(t){this._supersplat&&this._fly?.setConfig?this._fly.setConfig(t):this._cameraModeManager?.setFlyConfig(t)}getFlyCameraConfig(){if(this._supersplat&&this._fly)try{const t=this._fly;return{moveSpeed:t.moveSpeed,fastSpeedMultiplier:t.fastSpeedMultiplier,slowSpeedMultiplier:t.slowSpeedMultiplier,lookSensitivity:t.lookSensitivity,invertY:!!t.invertY,keyBindings:{...t.keyBindings||{}},smoothing:t.smoothing,friction:t.friction,enableCollision:!!t.enableCollision,minHeight:t.minHeight??null,maxHeight:t.maxHeight??null}}catch{return null}return this._cameraModeManager?.getFlyConfig()||null}getFlyCameraState(){if(this._supersplat&&this._fly?.getState)try{const t=this._fly.getState();return{mode:this._cameraMode,position:t.position,rotation:t.rotation,velocity:t.velocity,isMoving:t.isMoving}}catch{return null}return this._cameraModeManager?.getFlyState()||null}_setupScene(){this.app&&(this.app.scene.ambientLight=new H(.2,.2,.2))}_setupCamera(){if(!this.app)return;const t=new z_("camera");t.addComponent("camera",{clearColor:new H(.1,.1,.1),nearClip:.01,farClip:1e6}),this.app.root.addChild(t),this.entities.camera=t}_setupLighting(){if(!this.app)return;const t=new z_("light");t.addComponent("light",{type:0,color:new H(1,1,1),intensity:1,castShadows:!0}),t.setLocalEulerAngles(45,30,0),this.app.root.addChild(t),this.entities.light=t}_setupOrbitCamera(){if(!this.app||!this.entities.camera)return;!function(){if(void 0===JL)return;if(!n_)return;if(n_?.scripts?.has("orbitCamera"))return;const t=Lw("orbitCamera");t&&(t.attributes.add("distance",{type:"number",default:10}),t.attributes.add("minDistance",{type:"number",default:.1}),t.attributes.add("maxDistance",{type:"number",default:1e5}),t.attributes.add("orbitSensitivity",{type:"number",default:.3}),t.attributes.add("panSensitivity",{type:"number",default:1}),t.attributes.add("zoomSensitivity",{type:"number",default:.1}),t.attributes.add("enableNavigationCube",{type:"boolean",default:!1}),t.attributes.add("navigationCubeConfig",{type:"json",default:null}),t.prototype.initialize=function(){if(this.target=new K(0,0,0),this.distance=this.distance||10,this.pitch=-15,this.yaw=45,this.isOrbiting=!1,this.isPanning=!1,this._inputEnabled=!0,this.setupContextMenuPrevention(),this.app.mouse.on(fM,this.onMouseDown,this),this.app.mouse.on(_M,this.onMouseUp,this),this.app.mouse.on(mM,this.onMouseMove,this),this.app.mouse.on(gM,this.onMouseWheel,this),this.updateCameraPosition(),this.enableNavigationCube)try{let t=this.navigationCubeConfig||{};this.entity._navigationCubeConfig&&(t=this.entity._navigationCubeConfig),this.navigationCube=new Pz(t),this.navigationCube.initialize(this.app,this.entity,this,this.emitInteractionEvent)}catch(t){delete this.navigationCube}},t.prototype.setEnabled=function(t){this._inputEnabled=!!t,t||(this.isOrbiting=!1,this.isPanning=!1)},t.prototype.update=function(t){this.navigationCube&&"function"==typeof this.navigationCube.update&&this.navigationCube.update(t)},t.prototype.onMouseDown=function(t){!1!==this._inputEnabled&&(this.navigationCube&&"function"==typeof this.navigationCube.cancelTransition&&this.navigationCube.cancelTransition("manual-interaction"),0===t.button?(this.isOrbiting=!0,this.emitInteractionEvent?.("interaction-start","rotate")):2!==t.button&&1!==t.button||(this.isPanning=!0,this.emitInteractionEvent?.("interaction-start","pan")))},t.prototype.onMouseUp=function(){this.isOrbiting&&(this.isOrbiting=!1,this.emitInteractionEvent?.("interaction-end","rotate")),this.isPanning&&(this.isPanning=!1,this.emitInteractionEvent?.("interaction-end","pan"))},t.prototype.onMouseMove=function(t){if(!1!==this._inputEnabled)if(this.isOrbiting){const e=t.dx*this.orbitSensitivity,i=t.dy*this.orbitSensitivity;this.yaw-=e,this.pitch+=i,this.pitch=Math.max(-89,Math.min(89,this.pitch)),this.updateCameraPosition()}else if(this.isPanning){const e=this.distance*this.panSensitivity*.001,i=this.entity.getWorldTransform(),s=new K,n=new K;i.getX(s),i.getY(n);const r=s.clone().mulScalar(-t.dx*e).add(n.clone().mulScalar(t.dy*e));this.target.add(r),this.updateCameraPosition()}},t.prototype.onMouseWheel=function(t){if(!1===this._inputEnabled)return;this.navigationCube&&"function"==typeof this.navigationCube.cancelTransition&&this.navigationCube.cancelTransition("manual-interaction"),this.emitInteractionEvent?.("interaction-start","zoom");const e=Math.sign(t.wheel)*this.distance*this.zoomSensitivity;this.distance=Math.max(this.minDistance,Math.min(this.maxDistance,this.distance-e)),this.updateCameraPosition(),this.emitInteractionEvent?.("interaction-end","zoom")},t.prototype.updateCameraPosition=function(){const t=this.pitch*Math.PI/180,e=this.yaw*Math.PI/180,i=this.distance*Math.cos(t)*Math.sin(e),s=this.distance*Math.sin(t),n=this.distance*Math.cos(t)*Math.cos(e);this.entity.setPosition(new K(i,s,n).add(this.target)),this.entity.lookAt(this.target,K.UP),this.navigationCube&&"function"==typeof this.navigationCube.syncWithCamera&&this.navigationCube.syncWithCamera(this.pitch,this.yaw)},t.prototype.focus=function(t){const e=new K(0,0,0);let i=10,s=!1;if(t){const n=t.gsplat;if(n){const t=n.bounds||n.boundingBox;t?.center&&t.halfExtents?(e.copy(t.center),i=Math.max(1,t.halfExtents.length()),s=!0):"number"==typeof n.radius&&n.center&&(e.copy(n.center),i=Math.max(1,n.radius),s=!0)}if(!s&&t._calculateHierarchyBounds){const n=new ut;t.getWorldTransform(),t._calculateHierarchyBounds(n),n.halfExtents.length()>0&&(e.copy(n.center),i=Math.max(1,n.halfExtents.length()),s=!0)}}const n=this.entity.camera.fov*Math.PI/180,r=i/Math.sin(n/2)*1.5;this.target.copy(e),this.distance=Math.max(this.minDistance,Math.min(this.maxDistance,r)),this.pitch=-15,this.yaw=45,this.updateCameraPosition()},t.prototype.setupContextMenuPrevention=function(){[this.app.graphicsDevice.canvas,document.querySelector("canvas")].filter(Boolean).forEach(t=>{this._contextMenuHandler&&(t.removeEventListener("contextmenu",this._contextMenuHandler),t.removeEventListener("mousedown",this._mouseDownHandler),t.removeEventListener("mouseup",this._mouseUpHandler)),this._contextMenuHandler=t=>(t.preventDefault(),t.stopPropagation(),!1),this._mouseDownHandler=t=>{2===t.button&&(t.preventDefault(),t.stopPropagation())},this._mouseUpHandler=t=>{2===t.button&&(t.preventDefault(),t.stopPropagation())},t.addEventListener("contextmenu",this._contextMenuHandler,{passive:!1}),t.addEventListener("mousedown",this._mouseDownHandler,{passive:!1}),t.addEventListener("mouseup",this._mouseUpHandler,{passive:!1})})},t.prototype.destroy=function(){if(this.navigationCube&&"function"==typeof this.navigationCube.destroy){try{this.navigationCube.destroy()}catch(t){}delete this.navigationCube}[this.app?.graphicsDevice?.canvas,document.querySelector("canvas")].filter(Boolean).forEach(t=>{this._contextMenuHandler&&t.removeEventListener("contextmenu",this._contextMenuHandler),this._mouseDownHandler&&t.removeEventListener("mousedown",this._mouseDownHandler),this._mouseUpHandler&&t.removeEventListener("mouseup",this._mouseUpHandler)}),this.app?.mouse&&(this.app.mouse.off(fM,this.onMouseDown,this),this.app.mouse.off(_M,this.onMouseUp,this),this.app.mouse.off(mM,this.onMouseMove,this),this.app.mouse.off(gM,this.onMouseWheel,this))})}(),this.entities.camera.addComponent("script");const t={distance:10,minDistance:.1,maxDistance:1e5,orbitSensitivity:.3,panSensitivity:1,zoomSensitivity:.1};if(this._navigationCubeConfig&&!this.previewMode&&(t.enableNavigationCube=this._navigationCubeConfig.enabled||!1,this.entities.camera._navigationCubeConfig=this._navigationCubeConfig),this._orbit=this.entities.camera.script.create("orbitCamera",{attributes:t}),this._orbit.emitInteractionEvent=(t,e)=>{this.emit({type:t,detail:{type:e}})},this.previewMode&&this._orbit){const t=this._orbit;"function"==typeof t.setEnabled&&t.setEnabled(!1)}if(this.entities.camera.setPosition(0,0,10),this.entities.camera.lookAt(K.ZERO),!this.previewMode)try{iD();const t={moveSpeed:iV.moveSpeed,fastSpeedMultiplier:iV.fastSpeedMultiplier,slowSpeedMultiplier:iV.slowSpeedMultiplier,lookSensitivity:iV.lookSensitivity,invertY:iV.invertY,keyBindings:iV.keyBindings,smoothing:iV.smoothing,friction:iV.friction,enableCollision:iV.enableCollision,minHeight:iV.minHeight,maxHeight:iV.maxHeight};this._fly=this.entities.camera.script.create("flyCamera",{attributes:t}),this._fly&&(this._fly.emitFlyEvent=(t,e)=>{this.emit({type:t,detail:e})}),this._fly?.deactivate&&this._fly.deactivate(),this._cameraModeManager=new tD(this.app,this.entities.camera,this._orbit,this._fly,(t,e)=>{this.emit({type:t,detail:e})},"orbit")}catch(t){}}_setupStats(){if(!this.app||!this.enableStats||!this._onStatsUpdate)return;let t=0,e=performance.now();this._statsHandler=()=>{t++;const i=performance.now(),s=i-e;if(s>=1e3){const n=Math.round(1e3*t/s),r=t=>"object"==typeof t&&null!==t?t.total||0:Number(t)||0,a=r(this.app.stats.triangles),o=r(this.app.stats.drawCalls),l={fps:n,frameTime:Math.round(s/t*100)/100,triangles:a,drawCalls:o,memoryUsage:performance.memory?Math.round(performance.memory.usedJSHeapSize/1024/1024):0};this._onStatsUpdate(l),this.emit({type:"stats-update",detail:l}),t=0,e=i}},this.app.on("frameend",this._statsHandler)}_setupResolution(){if(!this.app)return;const t=this.app.graphicsDevice.canvas;if(t.style.display||(t.style.display="block"),t.style.width||(t.style.width="100%"),t.style.height||(t.style.height="100%"),t.parentElement){const e=t.parentElement.style;e.width||(e.width="100%"),e.height||(e.height="100%")}const e=(e,i)=>{t.width===e&&t.height===i||(t.width=e,t.height=i,this.app.resizeCanvas(e,i),this._orbit&&this._orbit.navigationCube&&"function"==typeof this._orbit.navigationCube.onCanvasResize&&this._orbit.navigationCube.onCanvasResize(),this._supersplat&&"function"==typeof this._supersplat.onCanvasResize&&this._supersplat.onCanvasResize())},i=()=>{const i=t.getBoundingClientRect(),s=window.devicePixelRatio||1,n=Math.floor(i.width*s),r=Math.floor(i.height*s);e(n,r)},s=t=>{let s=null,n=null;const r=t.devicePixelContentBoxSize;if(r&&r.length>0)s=Math.ceil(r[0].inlineSize),n=Math.ceil(r[0].blockSize);else{const e=t.contentBoxSize;if(e&&e.length>0){const t=window.devicePixelRatio||1;s=Math.ceil(e[0].inlineSize*t),n=Math.ceil(e[0].blockSize*t)}}null!==s&&null!==n?e(s,n):i()};if(i(),window.ResizeObserver){this._resizeObserver=new ResizeObserver(e=>{if(!e||0===e.length)return void i();const n=e.find(e=>e.target===t);if(n)s(n);else if(e.length>0){const t=e[0];t?s(t):i()}else i()});try{this._resizeObserver.observe(t,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(t)}t.parentElement&&this._resizeObserver.observe(t.parentElement)}const n=()=>{i()};window.addEventListener("resize",n),this._resizeHandler=n}updateCanvasResolution(){if(!this.app)return;const t=this.app.graphicsDevice.canvas,e=t.getBoundingClientRect(),i=window.devicePixelRatio||1,s=Math.floor(e.width*i),n=Math.floor(e.height*i);t.width===s&&t.height===n||(t.width=s,t.height=n,this.app.resizeCanvas(s,n),this._orbit&&this._orbit.navigationCube&&"function"==typeof this._orbit.navigationCube.onCanvasResize&&this._orbit.navigationCube.onCanvasResize(),this._supersplat&&"function"==typeof this._supersplat.onCanvasResize&&this._supersplat.onCanvasResize())}}function sV(t,e){return new CustomEvent(t,{detail:e})}class SplatViewerElement extends HTMLElement{constructor(){super(...arguments),this._core=null,this._canvas=null,this._config={...wz},this._isInitialized=!1,this._isDestroyed=!1,this._hostResizeObserver=null}static get observedAttributes(){return["src","width","height","enable-stats","auto-focus","max-splats","preview-mode","camera-position","camera-target","orbit-sensitivity","pan-sensitivity","zoom-sensitivity","min-distance","max-distance","enable-navigation-cube","navigation-cube-size","navigation-cube-transition","navigation-cube-parent-id"]}get src(){return this.getAttribute("src")}get width(){return this.getAttribute("width")}get height(){return this.getAttribute("height")}get enableStats(){return this.hasAttribute("enable-stats")}get autoFocus(){return this.hasAttribute("auto-focus")}get previewMode(){return this.hasAttribute("preview-mode")}get maxSplats(){return this.getAttribute("max-splats")}get cameraPosition(){return this.getAttribute("camera-position")}get cameraTarget(){return this.getAttribute("camera-target")}get orbitSensitivity(){return this.getAttribute("orbit-sensitivity")}get panSensitivity(){return this.getAttribute("pan-sensitivity")}get zoomSensitivity(){return this.getAttribute("zoom-sensitivity")}get minDistance(){return this.getAttribute("min-distance")}get maxDistance(){return this.getAttribute("max-distance")}get enableNavigationCube(){return this.hasAttribute("enable-navigation-cube")}get navigationCubeSize(){return this.getAttribute("navigation-cube-size")}get navigationCubeTransition(){return this.getAttribute("navigation-cube-transition")}get navigationCubeParentId(){return this.getAttribute("navigation-cube-parent-id")}set src(t){null===t?this.removeAttribute("src"):this.setAttribute("src",t)}set width(t){null===t?this.removeAttribute("width"):this.setAttribute("width",t)}set height(t){null===t?this.removeAttribute("height"):this.setAttribute("height",t)}set enableStats(t){t?this.setAttribute("enable-stats",""):this.removeAttribute("enable-stats")}set autoFocus(t){t?this.setAttribute("auto-focus",""):this.removeAttribute("auto-focus")}set previewMode(t){t?this.setAttribute("preview-mode",""):this.removeAttribute("preview-mode")}set maxSplats(t){null===t?this.removeAttribute("max-splats"):this.setAttribute("max-splats",t)}set cameraPosition(t){null===t?this.removeAttribute("camera-position"):this.setAttribute("camera-position",t)}set cameraTarget(t){null===t?this.removeAttribute("camera-target"):this.setAttribute("camera-target",t)}set orbitSensitivity(t){null===t?this.removeAttribute("orbit-sensitivity"):this.setAttribute("orbit-sensitivity",t)}set panSensitivity(t){null===t?this.removeAttribute("pan-sensitivity"):this.setAttribute("pan-sensitivity",t)}set zoomSensitivity(t){null===t?this.removeAttribute("zoom-sensitivity"):this.setAttribute("zoom-sensitivity",t)}set minDistance(t){null===t?this.removeAttribute("min-distance"):this.setAttribute("min-distance",t)}set maxDistance(t){null===t?this.removeAttribute("max-distance"):this.setAttribute("max-distance",t)}set enableNavigationCube(t){t?this.setAttribute("enable-navigation-cube",""):this.removeAttribute("enable-navigation-cube")}set navigationCubeSize(t){null===t?this.removeAttribute("navigation-cube-size"):this.setAttribute("navigation-cube-size",t)}set navigationCubeTransition(t){null===t?this.removeAttribute("navigation-cube-transition"):this.setAttribute("navigation-cube-transition",t)}set navigationCubeParentId(t){null===t?this.removeAttribute("navigation-cube-parent-id"):this.setAttribute("navigation-cube-parent-id",t)}connectedCallback(){this._isDestroyed||this._initialize()}disconnectedCallback(){this._destroy()}attributeChangedCallback(t,e,i){if(e!==i&&(null===i||this._validateAttribute(t,i)))switch(this._updateConfigFromAttributes(),t){case"src":this._handleSrcChange(i);break;case"width":case"height":this._handleSizeChange();break;case"enable-stats":this._handleStatsChange()}}_validateAttribute(t,e){switch(t){case"width":case"height":return/^(\d+(\.\d+)?(px|%|em|rem|vh|vw|vmin|vmax)?|\d+)$/.test(e);case"max-splats":const t=parseInt(e,10);return!isNaN(t)&&t>0;case"orbit-sensitivity":case"pan-sensitivity":case"zoom-sensitivity":const i=parseFloat(e);return!isNaN(i)&&i>0;case"min-distance":case"max-distance":const s=parseFloat(e);return!isNaN(s)&&s>0;case"camera-position":case"camera-target":try{const t=JSON.parse(e);return Array.isArray(t)&&3===t.length&&t.every(t=>"number"==typeof t&&!isNaN(t))}catch{return!1}case"src":return e.length>0;case"enable-stats":case"auto-focus":case"preview-mode":case"enable-navigation-cube":return!0;case"navigation-cube-size":const n=parseFloat(e);return!isNaN(n)&&n>0;case"navigation-cube-transition":const r=parseFloat(e);return!isNaN(r)&&r>0;case"navigation-cube-parent-id":return e.length>0;default:return!0}}async _initialize(){if(!this._isInitialized)try{this.style.display="block",this.style.position="relative",this.style.overflow="hidden",this.hasAttribute("width")||this.style.width||(this.style.width="100%"),this.hasAttribute("height")||this.style.height||(this.style.height="100%"),this._canvas=document.createElement("canvas"),this._canvas.style.display="block",this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.outline="none",this._canvas.style.userSelect="none",this._canvas.style.touchAction="none",this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("role","img"),this._canvas.setAttribute("aria-label","3D Splat Viewer"),this.appendChild(this._canvas);try{window.ResizeObserver&&(this._hostResizeObserver=new ResizeObserver(()=>{try{this._core?.updateCanvasResolution()}catch{}}),this._hostResizeObserver.observe(this),this.parentElement&&this._hostResizeObserver.observe(this.parentElement))}catch{}this._updateConfigFromAttributes(),this._core=new SplatViewerCore(this._config),this._core.init(this._canvas),this._setupEventListeners(),this._handleSizeChange(),await this._core.whenReady();const t=this.src;t&&await this.load(t),this._isInitialized=!0,this.dispatchEvent(sV("ready",void 0))}catch(t){this._cleanupOnError(),this.dispatchEvent(sV("error",{message:`Failed to initialize: ${t instanceof Error?t.message:"Unknown error"}`,code:"INIT_FAILED"}))}}_cleanupOnError(){try{this._core&&(this._core.destroy(),this._core=null),this._canvas&&this._canvas.parentNode&&(this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this._isInitialized=!1}catch(t){}}_destroy(){if(!this._isDestroyed)try{this._hostResizeObserver&&(this._hostResizeObserver.disconnect(),this._hostResizeObserver=null),this._core&&(this._core.destroy(),this._core=null),this._canvas&&this._canvas.parentNode&&(this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this._isDestroyed=!0,this._isInitialized=!1}catch(t){}}_updateConfigFromAttributes(){const t=function(t){const e={},i=t.getAttribute("auto-focus");null!==i&&(e.autoFocus=Cz(i));const s=t.getAttribute("enable-stats");null!==s&&(e.enableStats=Cz(s));const n=t.getAttribute("preview-mode");null!==n&&(e.previewMode=Cz(n));const r=t.getAttribute("max-splats");null!==r&&(e.maxSplats=Mz(r,wz.maxSplats));const a=t.getAttribute("camera-position"),o=t.getAttribute("camera-target");if(a||o){const t=Az(a),i=Az(o);e.camera={...wz.camera,...t&&{position:t},...i&&{target:i}}}const l=t.getAttribute("enable-navigation-cube");null!==l&&(e.navigationCube={...wz.navigationCube,enabled:Cz(l)});const h=t.getAttribute("navigation-cube-size");null!==h&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,cubeSize:Mz(h,wz.navigationCube.cubeSize)});const c=t.getAttribute("navigation-cube-transition");null!==c&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,transitionDuration:Mz(c,wz.navigationCube.transitionDuration)});const d=t.getAttribute("navigation-cube-parent-id");null!==d&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,enabled:!0,parentElementId:d});const u=t.getAttribute("navigation-cube-rotation-speed");return null!==u&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,continuousRotationSpeed:Mz(u,wz.navigationCube.continuousRotationSpeed)}),e}(this);var e,i;this._config=(e=wz,i=t,{...e,...i,camera:{...e.camera,...i.camera},navigationCube:{...e.navigationCube,...i.navigationCube}})}_validateSource(t){if(!t||"string"!=typeof t)return!1;if(0===t.trim().length)return!1;try{return new URL(t),!0}catch{return!!t.startsWith("data:")||!(!t.startsWith("./")&&!t.startsWith("../")&&t.includes("://"))}}async _handleSrcChange(t){if(this._core&&t)if(this._validateSource(t))try{await this.load(t)}catch(t){await this._handleError(t,"LOAD_FAILED")}else this.dispatchEvent(sV("error",{message:`Invalid source: ${t}`,code:"INVALID_SOURCE"}))}_handleSizeChange(){if(!this._canvas)return;const t=this.width,e=this.height;if(t){const e=/(px|%|em|rem|vh|vw|vmin|vmax)$/.test(t);this.style.width=e?t:`${t}px`}else this.style.width="100%";if(e){const t=/(px|%|em|rem|vh|vw|vmin|vmax)$/.test(e);this.style.height=t?e:`${e}px`}else this.style.height="100%";this._canvas.style.width="100%",this._canvas.style.height="100%"}_handleStatsChange(){this._core}_setupEventListeners(){this._core&&(this._core.on("loading-start",t=>{this.dispatchEvent(sV("loading-start",t.detail))}),this._core.on("loading-progress",t=>{this.dispatchEvent(sV("loading-progress",t.detail))}),this._core.on("loaded",t=>{this.dispatchEvent(sV("loaded",t.detail))}),this._core.on("error",t=>{this.dispatchEvent(sV("error",t.detail))}),this._core.on("camera-change",t=>{this.dispatchEvent(sV("camera-change",t.detail))}),this._core.on("interaction-start",t=>{this.dispatchEvent(sV("interaction-start",t.detail))}),this._core.on("interaction-end",t=>{this.dispatchEvent(sV("interaction-end",t.detail))}),this._core.on("camera-mode-changed",t=>{this.dispatchEvent(sV("camera-mode-changed",t.detail))}),this._core.on("fly-camera-move",t=>{this.dispatchEvent(sV("fly-camera-move",t.detail))}),this._core.on("fly-camera-look",t=>{this.dispatchEvent(sV("fly-camera-look",t.detail))}),this._core.on("camera-fov-changed",t=>{this.dispatchEvent(sV("camera-fov-changed",t.detail))}),this._core.on("background-color-changed",t=>{this.dispatchEvent(sV("background-color-changed",t.detail))}),this._core.on("splat-center-size-changed",t=>{this.dispatchEvent(sV("splat-center-size-changed",t.detail))}),this._core.on("spherical-harmonics-bands-changed",t=>{this.dispatchEvent(sV("spherical-harmonics-bands-changed",t.detail))}),this._core.on("model-added",t=>{this.dispatchEvent(sV("model-added",t.detail))}),this._core.on("model-removed",t=>{this.dispatchEvent(sV("model-removed",t.detail))}),this._core.on("scene-cleared",t=>{this.dispatchEvent(sV("scene-cleared",t.detail))}))}async load(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");if("string"==typeof t){if(!this._validateSource(t))throw new Error(`Invalid source string: ${t}`)}else if(t instanceof File){if(0===t.size)throw new Error("File is empty")}else{if(!(t instanceof Blob))throw new Error("Invalid source type. Expected string, File, or Blob.");if(0===t.size)throw new Error("Blob is empty")}try{return await this._core.load(t,e)}catch(t){if(await this._handleError(t,"LOAD_FAILED"),t instanceof Error)throw new Error(`Failed to load model: ${t.message}`);throw new Error("Failed to load model: Unknown error")}}async loadFile(t,e){return this.load(t,e)}async loadBlob(t,e){return this.load(t,e)}focus(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.focus(t)}setCameraPosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraPosition(t)}setCameraTarget(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraTarget(t)}resetCamera(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.resetCamera()}clear(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clear()}getDebugInfo(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.debugInfo()}get isReady(){return this._isInitialized&&!this._isDestroyed&&null!==this._core}get config(){return{...this._config}}async _handleError(t,e){const i="string"==typeof t?t:t?.message||"Unknown error";this.dispatchEvent(sV("error",{message:e?`${e}: ${i}`:i,code:e||"ERROR"}))}async addModel(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return await this._core.addModel(t,e)}removeModel(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.removeModel(t)}getModels(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModels()}getModelStats(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModelStats(t)}getAllModelStats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllModelStats()}getSceneStats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSceneStats()}setModelVisible(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelVisible(t,e)}setModelsVisibleByName(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelsVisibleByName(t,e)}setCameraMode(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraMode(t)}getCameraMode(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getCameraMode()}setFlyCameraConfig(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setFlyCameraConfig(t)}getFlyCameraConfig(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraConfig()}getFlyCameraState(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraState()}setCameraFOV(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraFOV(t)}getCameraFOV(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getCameraFOV()}async animateCameraFOV(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.animateCameraFOV(t,e)}setFlyCameraSpeed(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setFlyCameraSpeed(t)}getFlyCameraSpeed(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraSpeed()}setBackgroundColor(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBackgroundColor(t)}getBackgroundColor(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBackgroundColor()}async animateBackgroundColor(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.animateBackgroundColor(t,e)}async setSkyboxEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.setSkyboxEnabled(t)}isSkyboxEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isSkyboxEnabled()}setSplatCenterSize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSplatCenterSize(t)}getSplatCenterSize(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSplatCenterSize()}setSphericalHarmonicsBands(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSphericalHarmonicsBands(t)}getSphericalHarmonicsBands(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSphericalHarmonicsBands()}setGridEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setGridEnabled(t)}isGridEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isGridEnabled()}setBoundingBoxEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoundingBoxEnabled(t)}isBoundingBoxEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isBoundingBoxEnabled()}setBoundingBoxSelection(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoundingBoxSelection(t)}getBoundingBoxSelection(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoundingBoxSelection()}createSelectionBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.createSelectionBox(t)}removeSelectionBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.removeSelectionBox(t)}clearSelectionBoxes(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSelectionBoxes()}setBoxSize(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxSize(t,e,i,s)}getBoxSize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoxSize(t)}setBoxPosition(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxPosition(t,e,i,s)}getBoxPosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoxPosition(t)}setBoxColor(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxColor(t,e,i,s)}showBox(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.showBox(t,e)}getAllSelectionBoxes(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllSelectionBoxes()}getSelectedBoxId(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedBoxId()}selectBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectBox(t)}setBoxSelectionEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoxSelectionEnabled(t)}isBoxSelectionEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isBoxSelectionEnabled()}createSelectionSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.createSelectionSphere(t)}removeSelectionSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.removeSelectionSphere(t)}clearSelectionSpheres(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSelectionSpheres()}setSphereRadius(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSphereRadius(t,e)}getSphereRadius(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSphereRadius(t)}setSpherePosition(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSpherePosition(t,e,i,s)}getSpherePosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSpherePosition(t)}setSphereColor(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSphereColor(t,e,i,s)}showSphere(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.showSphere(t,e)}getAllSelectionSpheres(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllSelectionSpheres()}getSelectedSphereId(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedSphereId()}selectSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSphere(t)}setSphereSelectionEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSphereSelectionEnabled(t)}isSphereSelectionEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isSphereSelectionEnabled()}selectSplatsInSphereById(t,e,i=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInSphereById(t,e,i)}getSplatDataDebugInfo(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSplatDataDebugInfo(t)}selectSplatsInBox(t,e,i=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInBox(t,e,i)}selectSplatsInSphere(t,e,i,s=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInSphere(new K(t.x,t.y,t.z),e,i,s)}clearSplatSelection(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSplatSelection()}getSelectedSplats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedSplats()}setHighlightEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightEnabled(t)}isHighlightEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isHighlightEnabled()}setHighlightColor(t,e,i,s=.7){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightColor(t,e,i,s)}getHighlightColor(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getHighlightColor()}setHighlightMode(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightMode(t)}getHighlightMode(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getHighlightMode()}setHighlightOverlayStyle(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightOverlayStyle(t)}setHighlightOverlaySize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightOverlaySize(t)}setOutlineEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setOutlineEnabled(t)}isOutlineEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isOutlineEnabled()}applyTransformMatrix(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.applyTransformMatrix(t,e)}setModelPosition(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelPosition(t,e)}setModelRotation(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelRotation(t,e)}setModelScale(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelScale(t,e)}getModelTransform(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModelTransform(t)}resetModelTransform(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.resetModelTransform(t)}}customElements.get("splat-viewer")||customElements.define("splat-viewer",SplatViewerElement),t.SplatViewerElement=SplatViewerElement,t.default=SplatViewerElement,Object.defineProperty(t,"__esModule",{value:!0})});
|
|
6
|
+
*/const pD="157",fD=0,mD=1,_D=2,gD=100,vD=101,yD=102,SD=200,xD=201,TD=202,ED=203,bD=204,wD=205,AD=206,CD=207,MD=208,PD=209,RD=210,LD=301,DD=302,ID=306,OD=1e3,ND=1001,FD=1002,UD=1003,BD=1004,zD=1005,kD=1006,VD=1007,HD=1008,GD=1009,WD=1012,XD=1013,YD=1014,qD=1015,jD=1016,$D=1020,KD=1023,ZD=1026,QD=1027,JD=33776,tI=33777,eI=33778,iI=33779,sI=36492,nI=3001,rI="",aI="srgb",oI="srgb-linear",lI="display-p3",hI="display-p3-linear",cI="linear",dI="srgb",uI="rec709",pI="p3",fI=7680,mI=512,_I=513,gI=514,vI=515,yI=516,SI=517,xI=518,TI=519,EI="300 es",bI=1035,wI=2e3,AI=2001;class CI{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const i=this._listeners;return void 0!==i[t]&&-1!==i[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const i=this._listeners[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const i=e.slice(0);for(let e=0,s=i.length;e<s;e++)i[e].call(this,t);t.target=null}}}const MI=["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"],PI=Math.PI/180,RI=180/Math.PI;function LI(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return(MI[255&t]+MI[t>>8&255]+MI[t>>16&255]+MI[t>>24&255]+"-"+MI[255&e]+MI[e>>8&255]+"-"+MI[e>>16&15|64]+MI[e>>24&255]+"-"+MI[63&i|128]+MI[i>>8&255]+"-"+MI[i>>16&255]+MI[i>>24&255]+MI[255&s]+MI[s>>8&255]+MI[s>>16&255]+MI[s>>24&255]).toLowerCase()}function DI(t,e,i){return Math.max(e,Math.min(i,t))}function II(t,e,i){return(1-i)*t+i*e}function OI(t){return!(t&t-1)&&0!==t}function NI(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function FI(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function UI(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}class BI{constructor(t=0,e=0){BI.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(DI(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class zI{constructor(t,e,i,s,n,r,a,o,l){zI.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,a,o,l)}set(t,e,i,s,n,r,a,o,l){const h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=n,h[5]=o,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[3],o=i[6],l=i[1],h=i[4],c=i[7],d=i[2],u=i[5],p=i[8],f=s[0],m=s[3],_=s[6],g=s[1],v=s[4],y=s[7],S=s[2],x=s[5],T=s[8];return n[0]=r*f+a*g+o*S,n[3]=r*m+a*v+o*x,n[6]=r*_+a*y+o*T,n[1]=l*f+h*g+c*S,n[4]=l*m+h*v+c*x,n[7]=l*_+h*y+c*T,n[2]=d*f+u*g+p*S,n[5]=d*m+u*v+p*x,n[8]=d*_+u*y+p*T,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*n*h+i*a*o+s*n*l-s*r*o}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8],c=h*r-a*l,d=a*o-h*n,u=l*n-r*o,p=e*c+i*d+s*u;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return t[0]=c*f,t[1]=(s*l-h*i)*f,t[2]=(a*i-s*r)*f,t[3]=d*f,t[4]=(h*e-s*o)*f,t[5]=(s*n-a*e)*f,t[6]=u*f,t[7]=(i*o-l*e)*f,t[8]=(r*e-i*n)*f,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,n,r,a){const o=Math.cos(n),l=Math.sin(n);return this.set(i*o,i*l,-i*(o*r+l*a)+r+t,-s*l,s*o,-s*(-l*r+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(kI.makeScale(t,e)),this}rotate(t){return this.premultiply(kI.makeRotation(-t)),this}translate(t,e){return this.premultiply(kI.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<9;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const kI=new zI;function VI(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function HI(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function GI(){const t=HI("canvas");return t.style.display="block",t}const WI={};function XI(t){t in WI||(WI[t]=!0)}const YI=(new zI).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),qI=(new zI).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),jI={[oI]:{transfer:cI,primaries:uI,toReference:t=>t,fromReference:t=>t},[aI]:{transfer:dI,primaries:uI,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[hI]:{transfer:cI,primaries:pI,toReference:t=>t.applyMatrix3(qI),fromReference:t=>t.applyMatrix3(YI)},[lI]:{transfer:dI,primaries:pI,toReference:t=>t.convertSRGBToLinear().applyMatrix3(qI),fromReference:t=>t.applyMatrix3(YI).convertLinearToSRGB()}},$I=new Set([oI,hI]),KI={enabled:!0,_workingColorSpace:oI,get legacyMode(){return!this.enabled},set legacyMode(t){this.enabled=!t},get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!$I.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,i){if(!1===this.enabled||e===i||!e||!i)return t;const s=jI[e].toReference;return(0,jI[i].fromReference)(s(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return jI[t].primaries},getTransfer:function(t){return t===rI?cI:jI[t].transfer}};function ZI(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function QI(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let JI;class tO{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===JI&&(JI=HI("canvas")),JI.width=t.width,JI.height=t.height;const i=JI.getContext("2d");t instanceof ImageData?i.putImageData(t,0,0):i.drawImage(t,0,0,t.width,t.height),e=JI}return e.width>2048||e.height>2048?e.toDataURL("image/jpeg",.6):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=HI("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),n=s.data;for(let t=0;t<n.length;t++)n[t]=255*ZI(n[t]/255);return i.putImageData(s,0,0),e}if(t.data){const e=t.data.slice(0);for(let t=0;t<e.length;t++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[t]=Math.floor(255*ZI(e[t]/255)):e[t]=ZI(e[t]);return{data:e,width:t.width,height:t.height}}return t}}let eO=0;class iO{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:eO++}),this.uuid=LI(),this.data=t,this.version=0}set needsUpdate(t){!0===t&&this.version++}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.images[this.uuid])return t.images[this.uuid];const i={uuid:this.uuid,url:""},s=this.data;if(null!==s){let t;if(Array.isArray(s)){t=[];for(let e=0,i=s.length;e<i;e++)s[e].isDataTexture?t.push(sO(s[e].image)):t.push(sO(s[e]))}else t=sO(s);i.url=t}return e||(t.images[this.uuid]=i),i}}function sO(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?tO.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:{}}let nO=0;class rO extends CI{constructor(t=rO.DEFAULT_IMAGE,e=rO.DEFAULT_MAPPING,i=1001,s=1001,n=1006,r=1008,a=1023,o=1009,l=rO.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nO++}),this.uuid=LI(),this.name="",this.source=new iO(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=s,this.magFilter=n,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new BI(0,0),this.repeat=new BI(1,1),this.center=new BI(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new zI,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,"string"==typeof h?this.colorSpace=h:(XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===nI?aI:rI),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return(new this.constructor).copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).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&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(300!==this.mapping)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case OD:t.x=t.x-Math.floor(t.x);break;case ND:t.x=t.x<0?0:1;break;case FD:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case OD:t.y=t.y-Math.floor(t.y);break;case ND:t.y=t.y<0?0:1;break;case FD:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===aI?nI:3e3}set encoding(t){XI("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=t===nI?aI:rI}}rO.DEFAULT_IMAGE=null,rO.DEFAULT_MAPPING=300,rO.DEFAULT_ANISOTROPY=1;class aO{constructor(t=0,e=0,i=0,s=1){aO.prototype.isVector4=!0,this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){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: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+r[15]*n,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,n;const r=.01,a=.1,o=t.elements,l=o[0],h=o[4],c=o[8],d=o[1],u=o[5],p=o[9],f=o[2],m=o[6],_=o[10];if(Math.abs(h-d)<r&&Math.abs(c-f)<r&&Math.abs(p-m)<r){if(Math.abs(h+d)<a&&Math.abs(c+f)<a&&Math.abs(p+m)<a&&Math.abs(l+u+_-3)<a)return this.set(1,0,0,0),this;e=Math.PI;const t=(l+1)/2,o=(u+1)/2,g=(_+1)/2,v=(h+d)/4,y=(c+f)/4,S=(p+m)/4;return t>o&&t>g?t<r?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(t),s=v/i,n=y/i):o>g?o<r?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(o),i=v/s,n=S/s):g<r?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(g),i=y/n,s=S/n),this.set(i,s,n,e),this}let g=Math.sqrt((m-p)*(m-p)+(c-f)*(c-f)+(d-h)*(d-h));return Math.abs(g)<.001&&(g=1),this.x=(m-p)/g,this.y=(c-f)/g,this.z=(d-h)/g,this.w=Math.acos((l+u+_-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),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}}class oO extends CI{constructor(t=1,e=1,i={}){super(),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=1,this.scissor=new aO(0,0,t,e),this.scissorTest=!1,this.viewport=new aO(0,0,t,e);const s={width:t,height:e,depth:1};void 0!==i.encoding&&(XI("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),i.colorSpace=i.encoding===nI?aI:rI),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:kD,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},i),this.texture=new rO(s,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=i.generateMipmaps,this.texture.internalFormat=i.internalFormat,this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}setSize(t,e,i=1){this.width===t&&this.height===e&&this.depth===i||(this.width=t,this.height=e,this.depth=i,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=i,this.dispose()),this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return(new this.constructor).copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.isRenderTargetTexture=!0;const e=Object.assign({},t.texture.image);return this.texture.source=new iO(e),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,null!==t.depthTexture&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class lO extends oO{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class hO extends rO{constructor(t=null,e=1,i=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:s},this.magFilter=UD,this.minFilter=UD,this.wrapR=ND,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class cO extends rO{constructor(t=null,e=1,i=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:s},this.magFilter=UD,this.minFilter=UD,this.wrapR=ND,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class dO{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,a){let o=i[s+0],l=i[s+1],h=i[s+2],c=i[s+3];const d=n[r+0],u=n[r+1],p=n[r+2],f=n[r+3];if(0===a)return t[e+0]=o,t[e+1]=l,t[e+2]=h,void(t[e+3]=c);if(1===a)return t[e+0]=d,t[e+1]=u,t[e+2]=p,void(t[e+3]=f);if(c!==f||o!==d||l!==u||h!==p){let t=1-a;const e=o*d+l*u+h*p+c*f,i=e>=0?1:-1,s=1-e*e;if(s>Number.EPSILON){const n=Math.sqrt(s),r=Math.atan2(n,e*i);t=Math.sin(t*r)/n,a=Math.sin(a*r)/n}const n=a*i;if(o=o*t+d*n,l=l*t+u*n,h=h*t+p*n,c=c*t+f*n,t===1-a){const t=1/Math.sqrt(o*o+l*l+h*h+c*c);o*=t,l*=t,h*=t,c*=t}}t[e]=o,t[e+1]=l,t[e+2]=h,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,n,r){const a=i[s],o=i[s+1],l=i[s+2],h=i[s+3],c=n[r],d=n[r+1],u=n[r+2],p=n[r+3];return t[e]=a*p+h*c+o*u-l*d,t[e+1]=o*p+h*d+l*c-a*u,t[e+2]=l*p+h*u+a*d-o*c,t[e+3]=h*p-a*c-o*d-l*u,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e){const i=t._x,s=t._y,n=t._z,r=t._order,a=Math.cos,o=Math.sin,l=a(i/2),h=a(s/2),c=a(n/2),d=o(i/2),u=o(s/2),p=o(n/2);switch(r){case"XYZ":this._x=d*h*c+l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c-d*u*p;break;case"YXZ":this._x=d*h*c+l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c+d*u*p;break;case"ZXY":this._x=d*h*c-l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c-d*u*p;break;case"ZYX":this._x=d*h*c-l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c+d*u*p;break;case"YZX":this._x=d*h*c+l*u*p,this._y=l*u*c+d*h*p,this._z=l*h*p-d*u*c,this._w=l*h*c-d*u*p;break;case"XZY":this._x=d*h*c-l*u*p,this._y=l*u*c-d*h*p,this._z=l*h*p+d*u*c,this._w=l*h*c+d*u*p}return!1!==e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],a=e[5],o=e[9],l=e[2],h=e[6],c=e[10],d=i+a+c;if(d>0){const t=.5/Math.sqrt(d+1);this._w=.25/t,this._x=(h-o)*t,this._y=(n-l)*t,this._z=(r-s)*t}else if(i>a&&i>c){const t=2*Math.sqrt(1+i-a-c);this._w=(h-o)/t,this._x=.25*t,this._y=(s+r)/t,this._z=(n+l)/t}else if(a>c){const t=2*Math.sqrt(1+a-i-c);this._w=(n-l)/t,this._x=(s+r)/t,this._y=.25*t,this._z=(o+h)/t}else{const t=2*Math.sqrt(1+c-i-a);this._w=(r-s)/t,this._x=(n+l)/t,this._y=(o+h)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(DI(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(0===i)return this;const s=Math.min(1,e/i);return this.slerp(t,s),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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,n=t._z,r=t._w,a=e._x,o=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+s*l-n*o,this._y=s*h+r*o+n*a-i*l,this._z=n*h+r*l+i*o-s*a,this._w=r*h-i*a-s*o-n*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const i=this._x,s=this._y,n=this._z,r=this._w;let a=r*t._w+i*t._x+s*t._y+n*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=r,this._x=i,this._y=s,this._z=n,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*r+e*this._w,this._x=t*i+e*this._x,this._y=t*s+e*this._y,this._z=t*n+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),h=Math.atan2(l,a),c=Math.sin((1-e)*h)/l,d=Math.sin(e*h)/l;return this._w=r*c+this._w*d,this._x=i*c+this._x*d,this._y=s*c+this._y*d,this._z=n*c+this._z*d,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=Math.random(),e=Math.sqrt(1-t),i=Math.sqrt(t),s=2*Math.PI*Math.random(),n=2*Math.PI*Math.random();return this.set(e*Math.cos(s),i*Math.sin(n),i*Math.cos(n),e*Math.sin(s))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class uO{constructor(t=0,e=0,i=0){uO.prototype.isVector3=!0,this.x=t,this.y=e,this.z=i}set(t,e,i){return void 0===i&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(fO.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(fO.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,a=t.z,o=t.w,l=o*e+r*s-a*i,h=o*i+a*e-n*s,c=o*s+n*i-r*e,d=-n*e-r*i-a*s;return this.x=l*o+d*-n+h*-a-c*-r,this.y=h*o+d*-r+c*-n-l*-a,this.z=c*o+d*-a+l*-r-h*-n,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}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(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,a=e.y,o=e.z;return this.x=s*o-n*a,this.y=n*r-i*o,this.z=i*a-s*r,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return pO.copy(this).projectOnVector(t),this.sub(pO)}reflect(t){return this.sub(pO.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(DI(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=2*(Math.random()-.5),e=Math.random()*Math.PI*2,i=Math.sqrt(1-t**2);return this.x=i*Math.cos(e),this.y=i*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pO=new uO,fO=new dO;class mO{constructor(t=new uO(1/0,1/0,1/0),e=new uO(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(gO.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(gO.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=gO.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return(new this.constructor).copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.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(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){if(t.updateWorldMatrix(!1,!1),void 0!==t.boundingBox)null===t.boundingBox&&t.computeBoundingBox(),vO.copy(t.boundingBox),vO.applyMatrix4(t.matrixWorld),this.union(vO);else{const i=t.geometry;if(void 0!==i)if(e&&void 0!==i.attributes&&void 0!==i.attributes.position){const e=i.attributes.position;for(let i=0,s=e.count;i<s;i++)gO.fromBufferAttribute(e,i).applyMatrix4(t.matrixWorld),this.expandByPoint(gO)}else null===i.boundingBox&&i.computeBoundingBox(),vO.copy(i.boundingBox),vO.applyMatrix4(t.matrixWorld),this.union(vO)}const i=t.children;for(let t=0,s=i.length;t<s;t++)this.expandByObject(i[t],e);return this}containsPoint(t){return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y||t.z<this.min.z||t.z>this.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y||t.max.z<this.min.z||t.min.z>this.max.z)}intersectsSphere(t){return this.clampPoint(t.center,gO),gO.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(wO),AO.subVectors(this.max,wO),yO.subVectors(t.a,wO),SO.subVectors(t.b,wO),xO.subVectors(t.c,wO),TO.subVectors(SO,yO),EO.subVectors(xO,SO),bO.subVectors(yO,xO);let e=[0,-TO.z,TO.y,0,-EO.z,EO.y,0,-bO.z,bO.y,TO.z,0,-TO.x,EO.z,0,-EO.x,bO.z,0,-bO.x,-TO.y,TO.x,0,-EO.y,EO.x,0,-bO.y,bO.x,0];return!!PO(e,yO,SO,xO,AO)&&(e=[1,0,0,0,1,0,0,0,1],!!PO(e,yO,SO,xO,AO)&&(CO.crossVectors(TO,EO),e=[CO.x,CO.y,CO.z],PO(e,yO,SO,xO,AO)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,gO).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(gO).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(_O[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),_O[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),_O[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),_O[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),_O[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),_O[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),_O[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),_O[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(_O)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const _O=[new uO,new uO,new uO,new uO,new uO,new uO,new uO,new uO],gO=new uO,vO=new mO,yO=new uO,SO=new uO,xO=new uO,TO=new uO,EO=new uO,bO=new uO,wO=new uO,AO=new uO,CO=new uO,MO=new uO;function PO(t,e,i,s,n){for(let r=0,a=t.length-3;r<=a;r+=3){MO.fromArray(t,r);const a=n.x*Math.abs(MO.x)+n.y*Math.abs(MO.y)+n.z*Math.abs(MO.z),o=e.dot(MO),l=i.dot(MO),h=s.dot(MO);if(Math.max(-Math.max(o,l,h),Math.min(o,l,h))>a)return!1}return!0}const RO=new mO,LO=new uO,DO=new uO;class IO{constructor(t=new uO,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;void 0!==e?i.copy(e):RO.setFromPoints(t).getCenter(i);let s=0;for(let e=0,n=t.length;e<n;e++)s=Math.max(s,i.distanceToSquared(t[e]));return this.radius=Math.sqrt(s),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;LO.subVectors(t,this.center);const e=LO.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),i=.5*(t-this.radius);this.center.addScaledVector(LO,i/t),this.radius+=i}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(DO.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(LO.copy(t.center).add(DO)),this.expandByPoint(LO.copy(t.center).sub(DO))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const OO=new uO,NO=new uO,FO=new uO,UO=new uO,BO=new uO,zO=new uO,kO=new uO;class VO{constructor(t=new uO,e=new uO(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,OO)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=OO.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(OO.copy(this.origin).addScaledVector(this.direction,e),OO.distanceToSquared(t))}distanceSqToSegment(t,e,i,s){NO.copy(t).add(e).multiplyScalar(.5),FO.copy(e).sub(t).normalize(),UO.copy(this.origin).sub(NO);const n=.5*t.distanceTo(e),r=-this.direction.dot(FO),a=UO.dot(this.direction),o=-UO.dot(FO),l=UO.lengthSq(),h=Math.abs(1-r*r);let c,d,u,p;if(h>0)if(c=r*o-a,d=r*a-o,p=n*h,c>=0)if(d>=-p)if(d<=p){const t=1/h;c*=t,d*=t,u=c*(c+r*d+2*a)+d*(r*c+d+2*o)+l}else d=n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;else d=-n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;else d<=-p?(c=Math.max(0,-(-r*n+a)),d=c>0?-n:Math.min(Math.max(-n,-o),n),u=-c*c+d*(d+2*o)+l):d<=p?(c=0,d=Math.min(Math.max(-n,-o),n),u=d*(d+2*o)+l):(c=Math.max(0,-(r*n+a)),d=c>0?n:Math.min(Math.max(-n,-o),n),u=-c*c+d*(d+2*o)+l);else d=r>0?-n:n,c=Math.max(0,-(r*d+a)),u=-c*c+d*(d+2*o)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,c),s&&s.copy(NO).addScaledVector(FO,d),u}intersectSphere(t,e){OO.subVectors(t.center,this.origin);const i=OO.dot(this.direction),s=OO.dot(OO)-i*i,n=t.radius*t.radius;if(s>n)return null;const r=Math.sqrt(n-s),a=i-r,o=i+r;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return null===i?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,s,n,r,a,o;const l=1/this.direction.x,h=1/this.direction.y,c=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,s=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,s=(t.min.x-d.x)*l),h>=0?(n=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(n=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||n>s?null:((n>i||isNaN(i))&&(i=n),(r<s||isNaN(s))&&(s=r),c>=0?(a=(t.min.z-d.z)*c,o=(t.max.z-d.z)*c):(a=(t.max.z-d.z)*c,o=(t.min.z-d.z)*c),i>o||a>s?null:((a>i||i!=i)&&(i=a),(o<s||s!=s)&&(s=o),s<0?null:this.at(i>=0?i:s,e)))}intersectsBox(t){return null!==this.intersectBox(t,OO)}intersectTriangle(t,e,i,s,n){BO.subVectors(e,t),zO.subVectors(i,t),kO.crossVectors(BO,zO);let r,a=this.direction.dot(kO);if(a>0){if(s)return null;r=1}else{if(!(a<0))return null;r=-1,a=-a}UO.subVectors(this.origin,t);const o=r*this.direction.dot(zO.crossVectors(UO,zO));if(o<0)return null;const l=r*this.direction.dot(BO.cross(UO));if(l<0)return null;if(o+l>a)return null;const h=-r*UO.dot(kO);return h<0?null:this.at(h/a,n)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class HO{constructor(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m){HO.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m)}set(t,e,i,s,n,r,a,o,l,h,c,d,u,p,f,m){const _=this.elements;return _[0]=t,_[4]=e,_[8]=i,_[12]=s,_[1]=n,_[5]=r,_[9]=a,_[13]=o,_[2]=l,_[6]=h,_[10]=c,_[14]=d,_[3]=u,_[7]=p,_[11]=f,_[15]=m,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 HO).fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/GO.setFromMatrixColumn(t,0).length(),n=1/GO.setFromMatrixColumn(t,1).length(),r=1/GO.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),a=Math.sin(i),o=Math.cos(s),l=Math.sin(s),h=Math.cos(n),c=Math.sin(n);if("XYZ"===t.order){const t=r*h,i=r*c,s=a*h,n=a*c;e[0]=o*h,e[4]=-o*c,e[8]=l,e[1]=i+s*l,e[5]=t-n*l,e[9]=-a*o,e[2]=n-t*l,e[6]=s+i*l,e[10]=r*o}else if("YXZ"===t.order){const t=o*h,i=o*c,s=l*h,n=l*c;e[0]=t+n*a,e[4]=s*a-i,e[8]=r*l,e[1]=r*c,e[5]=r*h,e[9]=-a,e[2]=i*a-s,e[6]=n+t*a,e[10]=r*o}else if("ZXY"===t.order){const t=o*h,i=o*c,s=l*h,n=l*c;e[0]=t-n*a,e[4]=-r*c,e[8]=s+i*a,e[1]=i+s*a,e[5]=r*h,e[9]=n-t*a,e[2]=-r*l,e[6]=a,e[10]=r*o}else if("ZYX"===t.order){const t=r*h,i=r*c,s=a*h,n=a*c;e[0]=o*h,e[4]=s*l-i,e[8]=t*l+n,e[1]=o*c,e[5]=n*l+t,e[9]=i*l-s,e[2]=-l,e[6]=a*o,e[10]=r*o}else if("YZX"===t.order){const t=r*o,i=r*l,s=a*o,n=a*l;e[0]=o*h,e[4]=n-t*c,e[8]=s*c+i,e[1]=c,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=i*c+s,e[10]=t-n*c}else if("XZY"===t.order){const t=r*o,i=r*l,s=a*o,n=a*l;e[0]=o*h,e[4]=-c,e[8]=l*h,e[1]=t*c+n,e[5]=r*h,e[9]=i*c-s,e[2]=s*c-i,e[6]=a*h,e[10]=n*c+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(XO,t,YO)}lookAt(t,e,i){const s=this.elements;return $O.subVectors(t,e),0===$O.lengthSq()&&($O.z=1),$O.normalize(),qO.crossVectors(i,$O),0===qO.lengthSq()&&(1===Math.abs(i.z)?$O.x+=1e-4:$O.z+=1e-4,$O.normalize(),qO.crossVectors(i,$O)),qO.normalize(),jO.crossVectors($O,qO),s[0]=qO.x,s[4]=jO.x,s[8]=$O.x,s[1]=qO.y,s[5]=jO.y,s[9]=$O.y,s[2]=qO.z,s[6]=jO.z,s[10]=$O.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[4],o=i[8],l=i[12],h=i[1],c=i[5],d=i[9],u=i[13],p=i[2],f=i[6],m=i[10],_=i[14],g=i[3],v=i[7],y=i[11],S=i[15],x=s[0],T=s[4],E=s[8],b=s[12],w=s[1],A=s[5],C=s[9],M=s[13],P=s[2],R=s[6],L=s[10],D=s[14],I=s[3],O=s[7],N=s[11],F=s[15];return n[0]=r*x+a*w+o*P+l*I,n[4]=r*T+a*A+o*R+l*O,n[8]=r*E+a*C+o*L+l*N,n[12]=r*b+a*M+o*D+l*F,n[1]=h*x+c*w+d*P+u*I,n[5]=h*T+c*A+d*R+u*O,n[9]=h*E+c*C+d*L+u*N,n[13]=h*b+c*M+d*D+u*F,n[2]=p*x+f*w+m*P+_*I,n[6]=p*T+f*A+m*R+_*O,n[10]=p*E+f*C+m*L+_*N,n[14]=p*b+f*M+m*D+_*F,n[3]=g*x+v*w+y*P+S*I,n[7]=g*T+v*A+y*R+S*O,n[11]=g*E+v*C+y*L+S*N,n[15]=g*b+v*M+y*D+S*F,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[12],r=t[1],a=t[5],o=t[9],l=t[13],h=t[2],c=t[6],d=t[10],u=t[14];return t[3]*(+n*o*c-s*l*c-n*a*d+i*l*d+s*a*u-i*o*u)+t[7]*(+e*o*u-e*l*d+n*r*d-s*r*u+s*l*h-n*o*h)+t[11]*(+e*l*c-e*a*u-n*r*c+i*r*u+n*a*h-i*l*h)+t[15]*(-s*a*h-e*o*c+e*a*d+s*r*c-i*r*d+i*o*h)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],l=t[7],h=t[8],c=t[9],d=t[10],u=t[11],p=t[12],f=t[13],m=t[14],_=t[15],g=c*m*l-f*d*l+f*o*u-a*m*u-c*o*_+a*d*_,v=p*d*l-h*m*l-p*o*u+r*m*u+h*o*_-r*d*_,y=h*f*l-p*c*l+p*a*u-r*f*u-h*a*_+r*c*_,S=p*c*o-h*f*o-p*a*d+r*f*d+h*a*m-r*c*m,x=e*g+i*v+s*y+n*S;if(0===x)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/x;return t[0]=g*T,t[1]=(f*d*n-c*m*n-f*s*u+i*m*u+c*s*_-i*d*_)*T,t[2]=(a*m*n-f*o*n+f*s*l-i*m*l-a*s*_+i*o*_)*T,t[3]=(c*o*n-a*d*n-c*s*l+i*d*l+a*s*u-i*o*u)*T,t[4]=v*T,t[5]=(h*m*n-p*d*n+p*s*u-e*m*u-h*s*_+e*d*_)*T,t[6]=(p*o*n-r*m*n-p*s*l+e*m*l+r*s*_-e*o*_)*T,t[7]=(r*d*n-h*o*n+h*s*l-e*d*l-r*s*u+e*o*u)*T,t[8]=y*T,t[9]=(p*c*n-h*f*n-p*i*u+e*f*u+h*i*_-e*c*_)*T,t[10]=(r*f*n-p*a*n+p*i*l-e*f*l-r*i*_+e*a*_)*T,t[11]=(h*a*n-r*c*n-h*i*l+e*c*l+r*i*u-e*a*u)*T,t[12]=S*T,t[13]=(h*f*s-p*c*s+p*i*d-e*f*d-h*i*m+e*c*m)*T,t[14]=(p*a*s-r*f*s-p*i*o+e*f*o+r*i*m-e*a*m)*T,t[15]=(r*c*s-h*a*s+h*i*o-e*c*o-r*i*d+e*a*d)*T,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,a=t.y,o=t.z,l=n*r,h=n*a;return this.set(l*r+i,l*a-s*o,l*o+s*a,0,l*a+s*o,h*a+i,h*o-s*r,0,l*o-s*a,h*o+s*r,n*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,a=e._z,o=e._w,l=n+n,h=r+r,c=a+a,d=n*l,u=n*h,p=n*c,f=r*h,m=r*c,_=a*c,g=o*l,v=o*h,y=o*c,S=i.x,x=i.y,T=i.z;return s[0]=(1-(f+_))*S,s[1]=(u+y)*S,s[2]=(p-v)*S,s[3]=0,s[4]=(u-y)*x,s[5]=(1-(d+_))*x,s[6]=(m+g)*x,s[7]=0,s[8]=(p+v)*T,s[9]=(m-g)*T,s[10]=(1-(d+f))*T,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let n=GO.set(s[0],s[1],s[2]).length();const r=GO.set(s[4],s[5],s[6]).length(),a=GO.set(s[8],s[9],s[10]).length();this.determinant()<0&&(n=-n),t.x=s[12],t.y=s[13],t.z=s[14],WO.copy(this);const o=1/n,l=1/r,h=1/a;return WO.elements[0]*=o,WO.elements[1]*=o,WO.elements[2]*=o,WO.elements[4]*=l,WO.elements[5]*=l,WO.elements[6]*=l,WO.elements[8]*=h,WO.elements[9]*=h,WO.elements[10]*=h,e.setFromRotationMatrix(WO),i.x=n,i.y=r,i.z=a,this}makePerspective(t,e,i,s,n,r,a=2e3){const o=this.elements,l=2*n/(e-t),h=2*n/(i-s),c=(e+t)/(e-t),d=(i+s)/(i-s);let u,p;if(a===wI)u=-(r+n)/(r-n),p=-2*r*n/(r-n);else{if(a!==AI)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);u=-r/(r-n),p=-r*n/(r-n)}return o[0]=l,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=h,o[9]=d,o[13]=0,o[2]=0,o[6]=0,o[10]=u,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,i,s,n,r,a=2e3){const o=this.elements,l=1/(e-t),h=1/(i-s),c=1/(r-n),d=(e+t)*l,u=(i+s)*h;let p,f;if(a===wI)p=(r+n)*c,f=-2*c;else{if(a!==AI)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=n*c,f=-1*c}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-d,o[1]=0,o[5]=2*h,o[9]=0,o[13]=-u,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let t=0;t<16;t++)if(e[t]!==i[t])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const GO=new uO,WO=new HO,XO=new uO(0,0,0),YO=new uO(1,1,1),qO=new uO,jO=new uO,$O=new uO,KO=new HO,ZO=new dO;class QO{constructor(t=0,e=0,i=0,s=QO.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,n=s[0],r=s[4],a=s[8],o=s[1],l=s[5],h=s[9],c=s[2],d=s[6],u=s[10];switch(e){case"XYZ":this._y=Math.asin(DI(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,u),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-DI(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,u),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,n),this._z=0);break;case"ZXY":this._x=Math.asin(DI(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-c,u),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(o,n));break;case"ZYX":this._y=Math.asin(-DI(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(d,u),this._z=Math.atan2(o,n)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(DI(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-c,n)):(this._x=0,this._y=Math.atan2(a,u));break;case"XZY":this._z=Math.asin(-DI(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-h,u),this._y=0)}return this._order=e,!0===i&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return KO.makeRotationFromQuaternion(t),this.setFromRotationMatrix(KO,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return ZO.setFromEuler(this),this.setFromQuaternion(ZO,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}QO.DEFAULT_ORDER="XYZ";class JO{constructor(){this.mask=1}set(t){this.mask=1<<t>>>0}enable(t){this.mask|=1<<t}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t}disable(t){this.mask&=~(1<<t)}disableAll(){this.mask=0}test(t){return 0!==(this.mask&t.mask)}isEnabled(t){return!!(this.mask&1<<t)}}let tN=0;const eN=new uO,iN=new dO,sN=new HO,nN=new uO,rN=new uO,aN=new uO,oN=new dO,lN=new uO(1,0,0),hN=new uO(0,1,0),cN=new uO(0,0,1),dN={type:"added"},uN={type:"removed"};class pN extends CI{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:tN++}),this.uuid=LI(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=pN.DEFAULT_UP.clone();const t=new uO,e=new QO,i=new dO,s=new uO(1,1,1);e._onChange(function(){i.setFromEuler(e,!1)}),i._onChange(function(){e.setFromQuaternion(i,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new HO},normalMatrix:{value:new zI}}),this.matrix=new HO,this.matrixWorld=new HO,this.matrixAutoUpdate=pN.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.matrixWorldAutoUpdate=pN.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.layers=new JO,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return iN.setFromAxisAngle(t,e),this.quaternion.multiply(iN),this}rotateOnWorldAxis(t,e){return iN.setFromAxisAngle(t,e),this.quaternion.premultiply(iN),this}rotateX(t){return this.rotateOnAxis(lN,t)}rotateY(t){return this.rotateOnAxis(hN,t)}rotateZ(t){return this.rotateOnAxis(cN,t)}translateOnAxis(t,e){return eN.copy(t).applyQuaternion(this.quaternion),this.position.add(eN.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(lN,t)}translateY(t){return this.translateOnAxis(hN,t)}translateZ(t){return this.translateOnAxis(cN,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(sN.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?nN.copy(t):nN.set(t,e,i);const s=this.parent;this.updateWorldMatrix(!0,!1),rN.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?sN.lookAt(rN,nN,this.up):sN.lookAt(nN,rN,this.up),this.quaternion.setFromRotationMatrix(sN),s&&(sN.extractRotation(s.matrixWorld),iN.setFromRotationMatrix(sN),this.quaternion.premultiply(iN.invert()))}add(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return t===this||t&&t.isObject3D&&(null!==t.parent&&t.parent.remove(t),t.parent=this,this.children.push(t),t.dispatchEvent(dN)),this}remove(t){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.remove(arguments[t]);return this}const e=this.children.indexOf(t);return-1!==e&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(uN)),this}removeFromParent(){const t=this.parent;return null!==t&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),sN.copy(this.matrixWorld).invert(),null!==t.parent&&(t.parent.updateWorldMatrix(!0,!1),sN.multiply(t.parent.matrixWorld)),t.applyMatrix4(sN),this.add(t),t.updateWorldMatrix(!1,!0),this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,s=this.children.length;i<s;i++){const s=this.children[i].getObjectByProperty(t,e);if(void 0!==s)return s}}getObjectsByProperty(t,e){let i=[];this[t]===e&&i.push(this);for(let s=0,n=this.children.length;s<n;s++){const n=this.children[s].getObjectsByProperty(t,e);n.length>0&&(i=i.concat(n))}return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rN,t,aN),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rN,oN,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverse(t)}traverseVisible(t){if(!1===this.visible)return;t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;null!==e&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,s=e.length;i<s;i++){const s=e[i];!0!==s.matrixWorldAutoUpdate&&!0!==t||s.updateMatrixWorld(t)}}updateWorldMatrix(t,e){const i=this.parent;if(!0===t&&null!==i&&!0===i.matrixWorldAutoUpdate&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),!0===e){const t=this.children;for(let e=0,i=t.length;e<i;e++){const i=t[e];!0===i.matrixWorldAutoUpdate&&i.updateWorldMatrix(!1,!0)}}}toJSON(t){const e=void 0===t||"string"==typeof t,i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const s={};function n(e,i){return void 0===e[i.uuid]&&(e[i.uuid]=i.toJSON(t)),i.uuid}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),!0===this.castShadow&&(s.castShadow=!0),!0===this.receiveShadow&&(s.receiveShadow=!0),!1===this.visible&&(s.visible=!1),!1===this.frustumCulled&&(s.frustumCulled=!1),0!==this.renderOrder&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(s.instanceColor=this.instanceColor.toJSON())),this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=n(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const i=e.shapes;if(Array.isArray(i))for(let e=0,s=i.length;e<s;e++){const s=i[e];n(t.shapes,s)}else n(t.shapes,i)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(n(t.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const e=[];for(let i=0,s=this.material.length;i<s;i++)e.push(n(t.materials,this.material[i]));s.material=e}else s.material=n(t.materials,this.material);if(this.children.length>0){s.children=[];for(let e=0;e<this.children.length;e++)s.children.push(this.children[e].toJSON(t).object)}if(this.animations.length>0){s.animations=[];for(let e=0;e<this.animations.length;e++){const i=this.animations[e];s.animations.push(n(t.animations,i))}}if(e){const e=r(t.geometries),s=r(t.materials),n=r(t.textures),a=r(t.images),o=r(t.shapes),l=r(t.skeletons),h=r(t.animations),c=r(t.nodes);e.length>0&&(i.geometries=e),s.length>0&&(i.materials=s),n.length>0&&(i.textures=n),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),h.length>0&&(i.animations=h),c.length>0&&(i.nodes=c)}return i.object=s,i;function r(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e<t.children.length;e++){const i=t.children[e];this.add(i.clone())}return this}}pN.DEFAULT_UP=new uO(0,1,0),pN.DEFAULT_MATRIX_AUTO_UPDATE=!0,pN.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const fN=new uO,mN=new uO,_N=new uO,gN=new uO,vN=new uO,yN=new uO,SN=new uO,xN=new uO,TN=new uO,EN=new uO;let bN=!1;class wN{constructor(t=new uO,e=new uO,i=new uO){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,s){s.subVectors(i,e),fN.subVectors(t,e),s.cross(fN);const n=s.lengthSq();return n>0?s.multiplyScalar(1/Math.sqrt(n)):s.set(0,0,0)}static getBarycoord(t,e,i,s,n){fN.subVectors(s,e),mN.subVectors(i,e),_N.subVectors(t,e);const r=fN.dot(fN),a=fN.dot(mN),o=fN.dot(_N),l=mN.dot(mN),h=mN.dot(_N),c=r*l-a*a;if(0===c)return n.set(-2,-1,-1);const d=1/c,u=(l*o-a*h)*d,p=(r*h-a*o)*d;return n.set(1-u-p,p,u)}static containsPoint(t,e,i,s){return this.getBarycoord(t,e,i,s,gN),gN.x>=0&&gN.y>=0&&gN.x+gN.y<=1}static getUV(t,e,i,s,n,r,a,o){return!1===bN&&(bN=!0),this.getInterpolation(t,e,i,s,n,r,a,o)}static getInterpolation(t,e,i,s,n,r,a,o){return this.getBarycoord(t,e,i,s,gN),o.setScalar(0),o.addScaledVector(n,gN.x),o.addScaledVector(r,gN.y),o.addScaledVector(a,gN.z),o}static isFrontFacing(t,e,i,s){return fN.subVectors(i,e),mN.subVectors(t,e),fN.cross(mN).dot(s)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,s){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,i,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,s),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return fN.subVectors(this.c,this.b),mN.subVectors(this.a,this.b),.5*fN.cross(mN).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return wN.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return wN.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,i,s,n){return!1===bN&&(bN=!0),wN.getInterpolation(t,this.a,this.b,this.c,e,i,s,n)}getInterpolation(t,e,i,s,n){return wN.getInterpolation(t,this.a,this.b,this.c,e,i,s,n)}containsPoint(t){return wN.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return wN.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,s=this.b,n=this.c;let r,a;vN.subVectors(s,i),yN.subVectors(n,i),xN.subVectors(t,i);const o=vN.dot(xN),l=yN.dot(xN);if(o<=0&&l<=0)return e.copy(i);TN.subVectors(t,s);const h=vN.dot(TN),c=yN.dot(TN);if(h>=0&&c<=h)return e.copy(s);const d=o*c-h*l;if(d<=0&&o>=0&&h<=0)return r=o/(o-h),e.copy(i).addScaledVector(vN,r);EN.subVectors(t,n);const u=vN.dot(EN),p=yN.dot(EN);if(p>=0&&u<=p)return e.copy(n);const f=u*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(yN,a);const m=h*p-u*c;if(m<=0&&c-h>=0&&u-p>=0)return SN.subVectors(n,s),a=(c-h)/(c-h+(u-p)),e.copy(s).addScaledVector(SN,a);const _=1/(m+f+d);return r=f*_,a=d*_,e.copy(i).addScaledVector(vN,r).addScaledVector(yN,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let AN=0;class CN extends CI{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:AN++}),this.uuid=LI(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=gD,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=fI,this.stencilZFail=fI,this.stencilZPass=fI,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.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const i=t[e];if(void 0===i)continue;const s=this[e];void 0!==s&&(s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[e]=i)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function s(t){const e=[];for(const i in t){const s=t[i];delete s.metadata,e.push(s)}return e}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(i.blending=this.blending),0!==this.side&&(i.side=this.side),!0===this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=!0),i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.stencilWrite=this.stencilWrite,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaHash&&(i.alphaHash=!0),!0===this.alphaToCoverage&&(i.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=!0),!0===this.forceSinglePass&&(i.forceSinglePass=!0),!0===this.wireframe&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=!0),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),e){const e=s(t.textures),n=s(t.images);e.length>0&&(i.textures=e),n.length>0&&(i.images=n)}return i}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(null!==e){const t=e.length;i=new Array(t);for(let s=0;s!==t;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}const MN={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},PN={h:0,s:0,l:0},RN={h:0,s:0,l:0};function LN(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+6*(e-t)*(2/3-i):t}class DN{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(void 0===e&&void 0===i){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=aI){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,KI.toWorkingColorSpace(this,e),this}setRGB(t,e,i,s=KI.workingColorSpace){return this.r=t,this.g=e,this.b=i,KI.toWorkingColorSpace(this,s),this}setHSL(t,e,i,s=KI.workingColorSpace){if(t=function(t,e){return(t%e+e)%e}(t,1),e=DI(e,0,1),i=DI(i,0,1),0===e)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,n=2*i-s;this.r=LN(n,s,t+1/3),this.g=LN(n,s,t),this.b=LN(n,s,t-1/3)}return KI.toWorkingColorSpace(this,s),this}setStyle(t,e=aI){function i(t){void 0!==t&&parseFloat(t)}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let t;const n=s[1],r=s[2];switch(n){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setRGB(Math.min(255,parseInt(t[1],10))/255,Math.min(255,parseInt(t[2],10))/255,Math.min(255,parseInt(t[3],10))/255,e);if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setRGB(Math.min(100,parseInt(t[1],10))/100,Math.min(100,parseInt(t[2],10))/100,Math.min(100,parseInt(t[3],10))/100,e);break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(t[4]),this.setHSL(parseFloat(t[1])/360,parseFloat(t[2])/100,parseFloat(t[3])/100,e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=s[1],i=t.length;if(3===i)return this.setRGB(parseInt(t.charAt(0),16)/15,parseInt(t.charAt(1),16)/15,parseInt(t.charAt(2),16)/15,e);if(6===i)return this.setHex(parseInt(t,16),e)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=aI){const i=MN[t.toLowerCase()];return void 0!==i&&this.setHex(i,e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=ZI(t.r),this.g=ZI(t.g),this.b=ZI(t.b),this}copyLinearToSRGB(t){return this.r=QI(t.r),this.g=QI(t.g),this.b=QI(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=aI){return KI.fromWorkingColorSpace(IN.copy(this),t),65536*Math.round(DI(255*IN.r,0,255))+256*Math.round(DI(255*IN.g,0,255))+Math.round(DI(255*IN.b,0,255))}getHexString(t=aI){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=KI.workingColorSpace){KI.fromWorkingColorSpace(IN.copy(this),e);const i=IN.r,s=IN.g,n=IN.b,r=Math.max(i,s,n),a=Math.min(i,s,n);let o,l;const h=(a+r)/2;if(a===r)o=0,l=0;else{const t=r-a;switch(l=h<=.5?t/(r+a):t/(2-r-a),r){case i:o=(s-n)/t+(s<n?6:0);break;case s:o=(n-i)/t+2;break;case n:o=(i-s)/t+4}o/=6}return t.h=o,t.s=l,t.l=h,t}getRGB(t,e=KI.workingColorSpace){return KI.fromWorkingColorSpace(IN.copy(this),e),t.r=IN.r,t.g=IN.g,t.b=IN.b,t}getStyle(t=aI){KI.fromWorkingColorSpace(IN.copy(this),t);const e=IN.r,i=IN.g,s=IN.b;return t!==aI?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(255*e)},${Math.round(255*i)},${Math.round(255*s)})`}offsetHSL(t,e,i){return this.getHSL(PN),this.setHSL(PN.h+t,PN.s+e,PN.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(PN),t.getHSL(RN);const i=II(PN.h,RN.h,e),s=II(PN.s,RN.s,e),n=II(PN.l,RN.l,e);return this.setHSL(i,s,n),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,s=this.b,n=t.elements;return this.r=n[0]*e+n[3]*i+n[6]*s,this.g=n[1]*e+n[4]*i+n[7]*s,this.b=n[2]*e+n[5]*i+n[8]*s,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const IN=new DN;DN.NAMES=MN;class ON extends CN{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new DN(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.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const NN=new uO,FN=new BI;class UN{constructor(t,e,i=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=i,this.usage=35044,this.updateRange={offset:0,count:-1},this.gpuType=qD,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let s=0,n=this.itemSize;s<n;s++)this.array[t+s]=e.array[i+s];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(2===this.itemSize)for(let e=0,i=this.count;e<i;e++)FN.fromBufferAttribute(this,e),FN.applyMatrix3(t),this.setXY(e,FN.x,FN.y);else if(3===this.itemSize)for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyMatrix3(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyMatrix4(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.applyNormalMatrix(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)NN.fromBufferAttribute(this,e),NN.transformDirection(t),this.setXYZ(e,NN.x,NN.y,NN.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=FI(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=UI(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=FI(e,this.array)),e}setX(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=FI(e,this.array)),e}setY(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=FI(e,this.array)),e}setZ(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=FI(e,this.array)),e}setW(t,e){return this.normalized&&(e=UI(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,s){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array),s=UI(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this}setXYZW(t,e,i,s,n){return t*=this.itemSize,this.normalized&&(e=UI(e,this.array),i=UI(i,this.array),s=UI(s,this.array),n=UI(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this.array[t+3]=n,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(t.name=this.name),35044!==this.usage&&(t.usage=this.usage),0===this.updateRange.offset&&-1===this.updateRange.count||(t.updateRange=this.updateRange),t}}class BN extends UN{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class zN extends UN{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class kN extends UN{constructor(t,e,i){super(new Float32Array(t),e,i)}}let VN=0;const HN=new HO,GN=new pN,WN=new uO,XN=new mO,YN=new mO,qN=new uO;class jN extends CI{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:VN++}),this.uuid=LI(),this.name="",this.type="BufferGeometry",this.index=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(t){return Array.isArray(t)?this.index=new(VI(t)?zN:BN)(t,1):this.index=t,this}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const e=(new zI).getNormalMatrix(t);i.applyNormalMatrix(e),i.needsUpdate=!0}const s=this.attributes.tangent;return void 0!==s&&(s.transformDirection(t),s.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(t){return HN.makeRotationFromQuaternion(t),this.applyMatrix4(HN),this}rotateX(t){return HN.makeRotationX(t),this.applyMatrix4(HN),this}rotateY(t){return HN.makeRotationY(t),this.applyMatrix4(HN),this}rotateZ(t){return HN.makeRotationZ(t),this.applyMatrix4(HN),this}translate(t,e,i){return HN.makeTranslation(t,e,i),this.applyMatrix4(HN),this}scale(t,e,i){return HN.makeScale(t,e,i),this.applyMatrix4(HN),this}lookAt(t){return GN.lookAt(t),GN.updateMatrix(),this.applyMatrix4(GN.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(WN).negate(),this.translate(WN.x,WN.y,WN.z),this}setFromPoints(t){const e=[];for(let i=0,s=t.length;i<s;i++){const s=t[i];e.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new kN(e,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new mO);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)this.boundingBox.set(new uO(-1/0,-1/0,-1/0),new uO(1/0,1/0,1/0));else{if(void 0!==t){if(this.boundingBox.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t<i;t++){const i=e[t];XN.setFromBufferAttribute(i),this.morphTargetsRelative?(qN.addVectors(this.boundingBox.min,XN.min),this.boundingBox.expandByPoint(qN),qN.addVectors(this.boundingBox.max,XN.max),this.boundingBox.expandByPoint(qN)):(this.boundingBox.expandByPoint(XN.min),this.boundingBox.expandByPoint(XN.max))}}else this.boundingBox.makeEmpty();isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z)}}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new IO);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute)this.boundingSphere.set(new uO,1/0);else if(t){const i=this.boundingSphere.center;if(XN.setFromBufferAttribute(t),e)for(let t=0,i=e.length;t<i;t++){const i=e[t];YN.setFromBufferAttribute(i),this.morphTargetsRelative?(qN.addVectors(XN.min,YN.min),XN.expandByPoint(qN),qN.addVectors(XN.max,YN.max),XN.expandByPoint(qN)):(XN.expandByPoint(YN.min),XN.expandByPoint(YN.max))}XN.getCenter(i);let s=0;for(let e=0,n=t.count;e<n;e++)qN.fromBufferAttribute(t,e),s=Math.max(s,i.distanceToSquared(qN));if(e)for(let n=0,r=e.length;n<r;n++){const r=e[n],a=this.morphTargetsRelative;for(let e=0,n=r.count;e<n;e++)qN.fromBufferAttribute(r,e),a&&(WN.fromBufferAttribute(t,e),qN.add(WN)),s=Math.max(s,i.distanceToSquared(qN))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)}}computeTangents(){const t=this.index,e=this.attributes;if(null===t||void 0===e.position||void 0===e.normal||void 0===e.uv)return;const i=t.array,s=e.position.array,n=e.normal.array,r=e.uv.array,a=s.length/3;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new UN(new Float32Array(4*a),4));const o=this.getAttribute("tangent").array,l=[],h=[];for(let t=0;t<a;t++)l[t]=new uO,h[t]=new uO;const c=new uO,d=new uO,u=new uO,p=new BI,f=new BI,m=new BI,_=new uO,g=new uO;function v(t,e,i){c.fromArray(s,3*t),d.fromArray(s,3*e),u.fromArray(s,3*i),p.fromArray(r,2*t),f.fromArray(r,2*e),m.fromArray(r,2*i),d.sub(c),u.sub(c),f.sub(p),m.sub(p);const n=1/(f.x*m.y-m.x*f.y);isFinite(n)&&(_.copy(d).multiplyScalar(m.y).addScaledVector(u,-f.y).multiplyScalar(n),g.copy(u).multiplyScalar(f.x).addScaledVector(d,-m.x).multiplyScalar(n),l[t].add(_),l[e].add(_),l[i].add(_),h[t].add(g),h[e].add(g),h[i].add(g))}let y=this.groups;0===y.length&&(y=[{start:0,count:i.length}]);for(let t=0,e=y.length;t<e;++t){const e=y[t],s=e.start;for(let t=s,n=s+e.count;t<n;t+=3)v(i[t+0],i[t+1],i[t+2])}const S=new uO,x=new uO,T=new uO,E=new uO;function b(t){T.fromArray(n,3*t),E.copy(T);const e=l[t];S.copy(e),S.sub(T.multiplyScalar(T.dot(e))).normalize(),x.crossVectors(E,e);const i=x.dot(h[t])<0?-1:1;o[4*t]=S.x,o[4*t+1]=S.y,o[4*t+2]=S.z,o[4*t+3]=i}for(let t=0,e=y.length;t<e;++t){const e=y[t],s=e.start;for(let t=s,n=s+e.count;t<n;t+=3)b(i[t+0]),b(i[t+1]),b(i[t+2])}}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(void 0!==e){let i=this.getAttribute("normal");if(void 0===i)i=new UN(new Float32Array(3*e.count),3),this.setAttribute("normal",i);else for(let t=0,e=i.count;t<e;t++)i.setXYZ(t,0,0,0);const s=new uO,n=new uO,r=new uO,a=new uO,o=new uO,l=new uO,h=new uO,c=new uO;if(t)for(let d=0,u=t.count;d<u;d+=3){const u=t.getX(d+0),p=t.getX(d+1),f=t.getX(d+2);s.fromBufferAttribute(e,u),n.fromBufferAttribute(e,p),r.fromBufferAttribute(e,f),h.subVectors(r,n),c.subVectors(s,n),h.cross(c),a.fromBufferAttribute(i,u),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,f),a.add(h),o.add(h),l.add(h),i.setXYZ(u,a.x,a.y,a.z),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(f,l.x,l.y,l.z)}else for(let t=0,a=e.count;t<a;t+=3)s.fromBufferAttribute(e,t+0),n.fromBufferAttribute(e,t+1),r.fromBufferAttribute(e,t+2),h.subVectors(r,n),c.subVectors(s,n),h.cross(c),i.setXYZ(t+0,h.x,h.y,h.z),i.setXYZ(t+1,h.x,h.y,h.z),i.setXYZ(t+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)qN.fromBufferAttribute(t,e),qN.normalize(),t.setXYZ(e,qN.x,qN.y,qN.z)}toNonIndexed(){function t(t,e){const i=t.array,s=t.itemSize,n=t.normalized,r=new i.constructor(e.length*s);let a=0,o=0;for(let n=0,l=e.length;n<l;n++){a=t.isInterleavedBufferAttribute?e[n]*t.data.stride+t.offset:e[n]*s;for(let t=0;t<s;t++)r[o++]=i[a++]}return new UN(r,s,n)}if(null===this.index)return this;const e=new jN,i=this.index.array,s=this.attributes;for(const n in s){const r=t(s[n],i);e.setAttribute(n,r)}const n=this.morphAttributes;for(const s in n){const r=[],a=n[s];for(let e=0,s=a.length;e<s;e++){const s=t(a[e],i);r.push(s)}e.morphAttributes[s]=r}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let t=0,i=r.length;t<i;t++){const i=r[t];e.addGroup(i.start,i.count,i.materialIndex)}return e}toJSON(){const t={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,""!==this.name&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const i in e)void 0!==e[i]&&(t[i]=e[i]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const e in i){const s=i[e];t.data.attributes[e]=s.toJSON(t.data)}const s={};let n=!1;for(const e in this.morphAttributes){const i=this.morphAttributes[e],r=[];for(let e=0,s=i.length;e<s;e++){const s=i[e];r.push(s.toJSON(t.data))}r.length>0&&(s[e]=r,n=!0)}n&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;null!==i&&this.setIndex(i.clone(e));const s=t.attributes;for(const t in s){const i=s[t];this.setAttribute(t,i.clone(e))}const n=t.morphAttributes;for(const t in n){const i=[],s=n[t];for(let t=0,n=s.length;t<n;t++)i.push(s[t].clone(e));this.morphAttributes[t]=i}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let t=0,e=r.length;t<e;t++){const e=r[t];this.addGroup(e.start,e.count,e.materialIndex)}const a=t.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=t.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const $N=new HO,KN=new VO,ZN=new IO,QN=new uO,JN=new uO,tF=new uO,eF=new uO,iF=new uO,sF=new uO,nF=new BI,rF=new BI,aF=new BI,oF=new uO,lF=new uO,hF=new uO,cF=new uO,dF=new uO;class uF extends pN{constructor(t=new jN,e=new ON){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),void 0!==t.morphTargetInfluences&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),void 0!==t.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,e=Object.keys(t);if(e.length>0){const i=t[e[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=i.length;t<e;t++){const e=i[t].name||String(t);this.morphTargetInfluences.push(0),this.morphTargetDictionary[e]=t}}}}getVertexPosition(t,e){const i=this.geometry,s=i.attributes.position,n=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(s,t);const a=this.morphTargetInfluences;if(n&&a){sF.set(0,0,0);for(let i=0,s=n.length;i<s;i++){const s=a[i],o=n[i];0!==s&&(iF.fromBufferAttribute(o,t),r?sF.addScaledVector(iF,s):sF.addScaledVector(iF.sub(e),s))}e.add(sF)}return e}raycast(t,e){const i=this.geometry,s=this.material,n=this.matrixWorld;if(void 0!==s){if(null===i.boundingSphere&&i.computeBoundingSphere(),ZN.copy(i.boundingSphere),ZN.applyMatrix4(n),KN.copy(t.ray).recast(t.near),!1===ZN.containsPoint(KN.origin)){if(null===KN.intersectSphere(ZN,QN))return;if(KN.origin.distanceToSquared(QN)>(t.far-t.near)**2)return}$N.copy(n).invert(),KN.copy(t.ray).applyMatrix4($N),null!==i.boundingBox&&!1===KN.intersectsBox(i.boundingBox)||this._computeIntersections(t,e,KN)}}_computeIntersections(t,e,i){let s;const n=this.geometry,r=this.material,a=n.index,o=n.attributes.position,l=n.attributes.uv,h=n.attributes.uv1,c=n.attributes.normal,d=n.groups,u=n.drawRange;if(null!==a)if(Array.isArray(r))for(let n=0,o=d.length;n<o;n++){const o=d[n],p=r[o.materialIndex];for(let n=Math.max(o.start,u.start),r=Math.min(a.count,Math.min(o.start+o.count,u.start+u.count));n<r;n+=3){s=pF(this,p,t,i,l,h,c,a.getX(n),a.getX(n+1),a.getX(n+2)),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=o.materialIndex,e.push(s))}}else{for(let n=Math.max(0,u.start),o=Math.min(a.count,u.start+u.count);n<o;n+=3){s=pF(this,r,t,i,l,h,c,a.getX(n),a.getX(n+1),a.getX(n+2)),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}else if(void 0!==o)if(Array.isArray(r))for(let n=0,a=d.length;n<a;n++){const a=d[n],p=r[a.materialIndex];for(let n=Math.max(a.start,u.start),r=Math.min(o.count,Math.min(a.start+a.count,u.start+u.count));n<r;n+=3){s=pF(this,p,t,i,l,h,c,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),s.face.materialIndex=a.materialIndex,e.push(s))}}else{for(let n=Math.max(0,u.start),a=Math.min(o.count,u.start+u.count);n<a;n+=3){s=pF(this,r,t,i,l,h,c,n,n+1,n+2),s&&(s.faceIndex=Math.floor(n/3),e.push(s))}}}}function pF(t,e,i,s,n,r,a,o,l,h){t.getVertexPosition(o,JN),t.getVertexPosition(l,tF),t.getVertexPosition(h,eF);const c=function(t,e,i,s,n,r,a,o){let l;if(l=1===e.side?s.intersectTriangle(a,r,n,!0,o):s.intersectTriangle(n,r,a,0===e.side,o),null===l)return null;dF.copy(o),dF.applyMatrix4(t.matrixWorld);const h=i.ray.origin.distanceTo(dF);return h<i.near||h>i.far?null:{distance:h,point:dF.clone(),object:t}}(t,e,i,s,JN,tF,eF,cF);if(c){n&&(nF.fromBufferAttribute(n,o),rF.fromBufferAttribute(n,l),aF.fromBufferAttribute(n,h),c.uv=wN.getInterpolation(cF,JN,tF,eF,nF,rF,aF,new BI)),r&&(nF.fromBufferAttribute(r,o),rF.fromBufferAttribute(r,l),aF.fromBufferAttribute(r,h),c.uv1=wN.getInterpolation(cF,JN,tF,eF,nF,rF,aF,new BI),c.uv2=c.uv1),a&&(oF.fromBufferAttribute(a,o),lF.fromBufferAttribute(a,l),hF.fromBufferAttribute(a,h),c.normal=wN.getInterpolation(cF,JN,tF,eF,oF,lF,hF,new uO),c.normal.dot(s.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:h,normal:new uO,materialIndex:0};wN.getNormal(JN,tF,eF,t.normal),c.face=t}return c}class fF extends jN{constructor(t=1,e=1,i=1,s=1,n=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:s,heightSegments:n,depthSegments:r};const a=this;s=Math.floor(s),n=Math.floor(n),r=Math.floor(r);const o=[],l=[],h=[],c=[];let d=0,u=0;function p(t,e,i,s,n,r,p,f,m,_,g){const v=r/m,y=p/_,S=r/2,x=p/2,T=f/2,E=m+1,b=_+1;let w=0,A=0;const C=new uO;for(let r=0;r<b;r++){const a=r*y-x;for(let o=0;o<E;o++){const d=o*v-S;C[t]=d*s,C[e]=a*n,C[i]=T,l.push(C.x,C.y,C.z),C[t]=0,C[e]=0,C[i]=f>0?1:-1,h.push(C.x,C.y,C.z),c.push(o/m),c.push(1-r/_),w+=1}}for(let t=0;t<_;t++)for(let e=0;e<m;e++){const i=d+e+E*t,s=d+e+E*(t+1),n=d+(e+1)+E*(t+1),r=d+(e+1)+E*t;o.push(i,s,r),o.push(s,n,r),A+=6}a.addGroup(u,A,g),u+=A,d+=w}p("z","y","x",-1,-1,i,e,t,r,n,0),p("z","y","x",1,-1,i,e,-t,r,n,1),p("x","z","y",1,1,t,i,e,s,r,2),p("x","z","y",1,-1,t,i,-e,s,r,3),p("x","y","z",1,-1,t,e,i,s,n,4),p("x","y","z",-1,-1,t,e,-i,s,n,5),this.setIndex(o),this.setAttribute("position",new kN(l,3)),this.setAttribute("normal",new kN(h,3)),this.setAttribute("uv",new kN(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new fF(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}function mF(t){const e={};for(const i in t){e[i]={};for(const s in t[i]){const n=t[i][s];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?e[i][s]=null:e[i][s]=n.clone():Array.isArray(n)?e[i][s]=n.slice():e[i][s]=n}}return e}function _F(t){const e={};for(let i=0;i<t.length;i++){const s=mF(t[i]);for(const t in s)e[t]=s[t]}return e}function gF(t){return null===t.getRenderTarget()?t.outputColorSpace:KI.workingColorSpace}const vF={clone:mF,merge:_F};class yF extends CN{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==t&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=mF(t.uniforms),this.uniformsGroups=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].clone());return e}(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const i in this.uniforms){const s=this.uniforms[i].value;s&&s.isTexture?e.uniforms[i]={type:"t",value:s.toJSON(t).uuid}:s&&s.isColor?e.uniforms[i]={type:"c",value:s.getHex()}:s&&s.isVector2?e.uniforms[i]={type:"v2",value:s.toArray()}:s&&s.isVector3?e.uniforms[i]={type:"v3",value:s.toArray()}:s&&s.isVector4?e.uniforms[i]={type:"v4",value:s.toArray()}:s&&s.isMatrix3?e.uniforms[i]={type:"m3",value:s.toArray()}:s&&s.isMatrix4?e.uniforms[i]={type:"m4",value:s.toArray()}:e.uniforms[i]={value:s}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const t in this.extensions)!0===this.extensions[t]&&(i[t]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}}let SF=class extends pN{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new HO,this.projectionMatrix=new HO,this.projectionMatrixInverse=new HO,this.coordinateSystem=wI}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}};class xF extends SF{constructor(t=50,e=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*RI*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*PI*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*RI*Math.atan(Math.tan(.5*PI*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,i,s,n,r){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*PI*this.fov)/this.zoom,i=2*e,s=this.aspect*i,n=-.5*s;const r=this.view;if(null!==this.view&&this.view.enabled){const t=r.fullWidth,a=r.fullHeight;n+=r.offsetX*s/t,e-=r.offsetY*i/a,s*=r.width/t,i*=r.height/a}const a=this.filmOffset;0!==a&&(n+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+s,e,e-i,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const TF=-90;class EF extends pN{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new xF(TF,1,t,e);s.layers=this.layers,this.add(s);const n=new xF(TF,1,t,e);n.layers=this.layers,this.add(n);const r=new xF(TF,1,t,e);r.layers=this.layers,this.add(r);const a=new xF(TF,1,t,e);a.layers=this.layers,this.add(a);const o=new xF(TF,1,t,e);o.layers=this.layers,this.add(o);const l=new xF(TF,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,s,n,r,a,o]=e;for(const t of e)this.remove(t);if(t===wI)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.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),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==AI)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.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),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[n,r,a,o,l,h]=this.children,c=t.getRenderTarget(),d=t.getActiveCubeFace(),u=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const f=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,t.setRenderTarget(i,0,s),t.render(e,n),t.setRenderTarget(i,1,s),t.render(e,r),t.setRenderTarget(i,2,s),t.render(e,a),t.setRenderTarget(i,3,s),t.render(e,o),t.setRenderTarget(i,4,s),t.render(e,l),i.texture.generateMipmaps=f,t.setRenderTarget(i,5,s),t.render(e,h),t.setRenderTarget(c,d,u),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class bF extends rO{constructor(t,e,i,s,n,r,a,o,l,h){super(t=void 0!==t?t:[],e=void 0!==e?e:LD,i,s,n,r,a,o,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class wF extends lO{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const i={width:t,height:t,depth:1},s=[i,i,i,i,i,i];void 0!==e.encoding&&(XI("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),e.colorSpace=e.encoding===nI?aI:rI),this.texture=new bF(s,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:kD}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},s=new fF(5,5,5),n=new yF({name:"CubemapFromEquirect",uniforms:mF(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:1,blending:0});n.uniforms.tEquirect.value=e;const r=new uF(s,n),a=e.minFilter;e.minFilter===HD&&(e.minFilter=kD);return new EF(1,10,this).update(t,r),e.minFilter=a,r.geometry.dispose(),r.material.dispose(),this}clear(t,e,i,s){const n=t.getRenderTarget();for(let n=0;n<6;n++)t.setRenderTarget(this,n),t.clear(e,i,s);t.setRenderTarget(n)}}const AF=new uO,CF=new uO,MF=new zI;class PF{constructor(t=new uO(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,s){return this.normal.set(t,e,i),this.constant=s,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const s=AF.subVectors(i,e).cross(CF.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(s,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const i=t.delta(AF),s=this.normal.dot(i);if(0===s)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const n=-(t.start.dot(this.normal)+this.constant)/s;return n<0||n>1?null:e.copy(t.start).addScaledVector(i,n)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||MF.getNormalMatrix(t),s=this.coplanarPoint(AF).applyMatrix4(t),n=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(n),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const RF=new IO,LF=new uO;class DF{constructor(t=new PF,e=new PF,i=new PF,s=new PF,n=new PF,r=new PF){this.planes=[t,e,i,s,n,r]}set(t,e,i,s,n,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(s),a[4].copy(n),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=2e3){const i=this.planes,s=t.elements,n=s[0],r=s[1],a=s[2],o=s[3],l=s[4],h=s[5],c=s[6],d=s[7],u=s[8],p=s[9],f=s[10],m=s[11],_=s[12],g=s[13],v=s[14],y=s[15];if(i[0].setComponents(o-n,d-l,m-u,y-_).normalize(),i[1].setComponents(o+n,d+l,m+u,y+_).normalize(),i[2].setComponents(o+r,d+h,m+p,y+g).normalize(),i[3].setComponents(o-r,d-h,m-p,y-g).normalize(),i[4].setComponents(o-a,d-c,m-f,y-v).normalize(),e===wI)i[5].setComponents(o+a,d+c,m+f,y+v).normalize();else{if(e!==AI)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);i[5].setComponents(a,c,f,v).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),RF.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),RF.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(RF)}intersectsSprite(t){return RF.center.set(0,0,0),RF.radius=.7071067811865476,RF.applyMatrix4(t.matrixWorld),this.intersectsSphere(RF)}intersectsSphere(t){const e=this.planes,i=t.center,s=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(i)<s)return!1}return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const s=e[i];if(LF.x=s.normal.x>0?t.max.x:t.min.x,LF.y=s.normal.y>0?t.max.y:t.min.y,LF.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(LF)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function IF(){let t=null,e=!1,i=null,s=null;function n(e,r){i(e,r),s=t.requestAnimationFrame(n)}return{start:function(){!0!==e&&null!==i&&(s=t.requestAnimationFrame(n),e=!0)},stop:function(){t.cancelAnimationFrame(s),e=!1},setAnimationLoop:function(t){i=t},setContext:function(e){t=e}}}function OF(t,e){const i=e.isWebGL2,s=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),s.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const i=s.get(e);i&&(t.deleteBuffer(i.buffer),s.delete(e))},update:function(e,n){if(e.isGLBufferAttribute){const t=s.get(e);return void((!t||t.version<e.version)&&s.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version}))}e.isInterleavedBufferAttribute&&(e=e.data);const r=s.get(e);void 0===r?s.set(e,function(e,s){const n=e.array,r=e.usage,a=t.createBuffer();let o;if(t.bindBuffer(s,a),t.bufferData(s,n,r),e.onUploadCallback(),n instanceof Float32Array)o=t.FLOAT;else if(n instanceof Uint16Array)if(e.isFloat16BufferAttribute){if(!i)throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");o=t.HALF_FLOAT}else o=t.UNSIGNED_SHORT;else if(n instanceof Int16Array)o=t.SHORT;else if(n instanceof Uint32Array)o=t.UNSIGNED_INT;else if(n instanceof Int32Array)o=t.INT;else if(n instanceof Int8Array)o=t.BYTE;else if(n instanceof Uint8Array)o=t.UNSIGNED_BYTE;else{if(!(n instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+n);o=t.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:n.BYTES_PER_ELEMENT,version:e.version}}(e,n)):r.version<e.version&&(!function(e,s,n){const r=s.array,a=s.updateRange;t.bindBuffer(n,e),-1===a.count?t.bufferSubData(n,0,r):(i?t.bufferSubData(n,a.offset*r.BYTES_PER_ELEMENT,r,a.offset,a.count):t.bufferSubData(n,a.offset*r.BYTES_PER_ELEMENT,r.subarray(a.offset,a.offset+a.count)),a.count=-1),s.onUploadCallback()}(r.buffer,e,n),r.version=e.version)}}}class NF extends jN{constructor(t=1,e=1,i=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:s};const n=t/2,r=e/2,a=Math.floor(i),o=Math.floor(s),l=a+1,h=o+1,c=t/a,d=e/o,u=[],p=[],f=[],m=[];for(let t=0;t<h;t++){const e=t*d-r;for(let i=0;i<l;i++){const s=i*c-n;p.push(s,-e,0),f.push(0,0,1),m.push(i/a),m.push(1-t/o)}}for(let t=0;t<o;t++)for(let e=0;e<a;e++){const i=e+l*t,s=e+l*(t+1),n=e+1+l*(t+1),r=e+1+l*t;u.push(i,s,r),u.push(s,n,r)}this.setIndex(u),this.setAttribute("position",new kN(p,3)),this.setAttribute("normal",new kN(f,3)),this.setAttribute("uv",new kN(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new NF(t.width,t.height,t.widthSegments,t.heightSegments)}}const FF={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tanisotropyV /= material.anisotropy;\n\tmaterial.anisotropy = saturate( material.anisotropy );\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x - tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x + tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal;\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},UF={common:{diffuse:{value:new DN(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new zI},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new zI}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new zI}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new zI}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new zI},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new zI},normalScale:{value:new BI(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new zI},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new zI}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new zI}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new zI}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new DN(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new DN(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0},uvTransform:{value:new zI}},sprite:{diffuse:{value:new DN(16777215)},opacity:{value:1},center:{value:new BI(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new zI},alphaMap:{value:null},alphaMapTransform:{value:new zI},alphaTest:{value:0}}},BF={basic:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.fog]),vertexShader:FF.meshbasic_vert,fragmentShader:FF.meshbasic_frag},lambert:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,UF.lights,{emissive:{value:new DN(0)}}]),vertexShader:FF.meshlambert_vert,fragmentShader:FF.meshlambert_frag},phong:{uniforms:_F([UF.common,UF.specularmap,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,UF.lights,{emissive:{value:new DN(0)},specular:{value:new DN(1118481)},shininess:{value:30}}]),vertexShader:FF.meshphong_vert,fragmentShader:FF.meshphong_frag},standard:{uniforms:_F([UF.common,UF.envmap,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.roughnessmap,UF.metalnessmap,UF.fog,UF.lights,{emissive:{value:new DN(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:FF.meshphysical_vert,fragmentShader:FF.meshphysical_frag},toon:{uniforms:_F([UF.common,UF.aomap,UF.lightmap,UF.emissivemap,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.gradientmap,UF.fog,UF.lights,{emissive:{value:new DN(0)}}]),vertexShader:FF.meshtoon_vert,fragmentShader:FF.meshtoon_frag},matcap:{uniforms:_F([UF.common,UF.bumpmap,UF.normalmap,UF.displacementmap,UF.fog,{matcap:{value:null}}]),vertexShader:FF.meshmatcap_vert,fragmentShader:FF.meshmatcap_frag},points:{uniforms:_F([UF.points,UF.fog]),vertexShader:FF.points_vert,fragmentShader:FF.points_frag},dashed:{uniforms:_F([UF.common,UF.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:FF.linedashed_vert,fragmentShader:FF.linedashed_frag},depth:{uniforms:_F([UF.common,UF.displacementmap]),vertexShader:FF.depth_vert,fragmentShader:FF.depth_frag},normal:{uniforms:_F([UF.common,UF.bumpmap,UF.normalmap,UF.displacementmap,{opacity:{value:1}}]),vertexShader:FF.meshnormal_vert,fragmentShader:FF.meshnormal_frag},sprite:{uniforms:_F([UF.sprite,UF.fog]),vertexShader:FF.sprite_vert,fragmentShader:FF.sprite_frag},background:{uniforms:{uvTransform:{value:new zI},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:FF.background_vert,fragmentShader:FF.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:FF.backgroundCube_vert,fragmentShader:FF.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:FF.cube_vert,fragmentShader:FF.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:FF.equirect_vert,fragmentShader:FF.equirect_frag},distanceRGBA:{uniforms:_F([UF.common,UF.displacementmap,{referencePosition:{value:new uO},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:FF.distanceRGBA_vert,fragmentShader:FF.distanceRGBA_frag},shadow:{uniforms:_F([UF.lights,UF.fog,{color:{value:new DN(0)},opacity:{value:1}}]),vertexShader:FF.shadow_vert,fragmentShader:FF.shadow_frag}};BF.physical={uniforms:_F([BF.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new zI},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new zI},clearcoatNormalScale:{value:new BI(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new zI},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new zI},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new zI},sheen:{value:0},sheenColor:{value:new DN(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new zI},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new zI},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new zI},transmissionSamplerSize:{value:new BI},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new zI},attenuationDistance:{value:0},attenuationColor:{value:new DN(0)},specularColor:{value:new DN(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new zI},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new zI},anisotropyVector:{value:new BI},anisotropyMap:{value:null},anisotropyMapTransform:{value:new zI}}]),vertexShader:FF.meshphysical_vert,fragmentShader:FF.meshphysical_frag};const zF={r:0,b:0,g:0};function kF(t,e,i,s,n,r,a){const o=new DN(0);let l,h,c=!0===r?0:1,d=null,u=0,p=null;function f(e,i){e.getRGB(zF,gF(t)),s.buffers.color.setClear(zF.r,zF.g,zF.b,i,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),c=e,f(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(t){c=t,f(o,c)},render:function(r,m){let _=!1,g=!0===m.isScene?m.background:null;if(g&&g.isTexture){g=(m.backgroundBlurriness>0?i:e).get(g)}null===g?f(o,c):g&&g.isColor&&(f(g,1),_=!0);const v=t.xr.getEnvironmentBlendMode();"additive"===v?s.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===v&&s.buffers.color.setClear(0,0,0,0,a),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),g&&(g.isCubeTexture||g.mapping===ID)?(void 0===h&&(h=new uF(new fF(1,1,1),new yF({name:"BackgroundCubeMaterial",uniforms:mF(BF.backgroundCube.uniforms),vertexShader:BF.backgroundCube.vertexShader,fragmentShader:BF.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(t,e,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h.material.uniforms.envMap.value=g,h.material.uniforms.flipEnvMap.value=g.isCubeTexture&&!1===g.isRenderTargetTexture?-1:1,h.material.uniforms.backgroundBlurriness.value=m.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=m.backgroundIntensity,h.material.toneMapped=KI.getTransfer(g.colorSpace)!==dI,d===g&&u===g.version&&p===t.toneMapping||(h.material.needsUpdate=!0,d=g,u=g.version,p=t.toneMapping),h.layers.enableAll(),r.unshift(h,h.geometry,h.material,0,0,null)):g&&g.isTexture&&(void 0===l&&(l=new uF(new NF(2,2),new yF({name:"BackgroundMaterial",uniforms:mF(BF.background.uniforms),vertexShader:BF.background.vertexShader,fragmentShader:BF.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=g,l.material.uniforms.backgroundIntensity.value=m.backgroundIntensity,l.material.toneMapped=KI.getTransfer(g.colorSpace)!==dI,!0===g.matrixAutoUpdate&&g.updateMatrix(),l.material.uniforms.uvTransform.value.copy(g.matrix),d===g&&u===g.version&&p===t.toneMapping||(l.material.needsUpdate=!0,d=g,u=g.version,p=t.toneMapping),l.layers.enableAll(),r.unshift(l,l.geometry,l.material,0,0,null))}}}function VF(t,e,i,s){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r=s.isWebGL2?null:e.get("OES_vertex_array_object"),a=s.isWebGL2||null!==r,o={},l=p(null);let h=l,c=!1;function d(e){return s.isWebGL2?t.bindVertexArray(e):r.bindVertexArrayOES(e)}function u(e){return s.isWebGL2?t.deleteVertexArray(e):r.deleteVertexArrayOES(e)}function p(t){const e=[],i=[],s=[];for(let t=0;t<n;t++)e[t]=0,i[t]=0,s[t]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:e,enabledAttributes:i,attributeDivisors:s,object:t,attributes:{},index:null}}function f(){const t=h.newAttributes;for(let e=0,i=t.length;e<i;e++)t[e]=0}function m(t){_(t,0)}function _(i,n){const r=h.newAttributes,a=h.enabledAttributes,o=h.attributeDivisors;if(r[i]=1,0===a[i]&&(t.enableVertexAttribArray(i),a[i]=1),o[i]!==n){(s.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[s.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](i,n),o[i]=n}}function g(){const e=h.newAttributes,i=h.enabledAttributes;for(let s=0,n=i.length;s<n;s++)i[s]!==e[s]&&(t.disableVertexAttribArray(s),i[s]=0)}function v(e,i,s,n,r,a,o){!0===o?t.vertexAttribIPointer(e,i,s,r,a):t.vertexAttribPointer(e,i,s,n,r,a)}function y(){S(),c=!0,h!==l&&(h=l,d(h.object))}function S(){l.geometry=null,l.program=null,l.wireframe=!1}return{setup:function(n,l,u,y,S){let x=!1;if(a){const e=function(e,i,n){const a=!0===n.wireframe;let l=o[e.id];void 0===l&&(l={},o[e.id]=l);let h=l[i.id];void 0===h&&(h={},l[i.id]=h);let c=h[a];void 0===c&&(c=p(s.isWebGL2?t.createVertexArray():r.createVertexArrayOES()),h[a]=c);return c}(y,u,l);h!==e&&(h=e,d(h.object)),x=function(t,e,i,s){const n=h.attributes,r=e.attributes;let a=0;const o=i.getAttributes();for(const e in o){if(o[e].location>=0){const i=n[e];let s=r[e];if(void 0===s&&("instanceMatrix"===e&&t.instanceMatrix&&(s=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(s=t.instanceColor)),void 0===i)return!0;if(i.attribute!==s)return!0;if(s&&i.data!==s.data)return!0;a++}}return h.attributesNum!==a||h.index!==s}(n,y,u,S),x&&function(t,e,i,s){const n={},r=e.attributes;let a=0;const o=i.getAttributes();for(const e in o){if(o[e].location>=0){let i=r[e];void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor));const s={};s.attribute=i,i&&i.data&&(s.data=i.data),n[e]=s,a++}}h.attributes=n,h.attributesNum=a,h.index=s}(n,y,u,S)}else{const t=!0===l.wireframe;h.geometry===y.id&&h.program===u.id&&h.wireframe===t||(h.geometry=y.id,h.program=u.id,h.wireframe=t,x=!0)}null!==S&&i.update(S,t.ELEMENT_ARRAY_BUFFER),(x||c)&&(c=!1,function(n,r,a,o){if(!1===s.isWebGL2&&(n.isInstancedMesh||o.isInstancedBufferGeometry)&&null===e.get("ANGLE_instanced_arrays"))return;f();const l=o.attributes,h=a.getAttributes(),c=r.defaultAttributeValues;for(const e in h){const r=h[e];if(r.location>=0){let a=l[e];if(void 0===a&&("instanceMatrix"===e&&n.instanceMatrix&&(a=n.instanceMatrix),"instanceColor"===e&&n.instanceColor&&(a=n.instanceColor)),void 0!==a){const e=a.normalized,l=a.itemSize,h=i.get(a);if(void 0===h)continue;const c=h.buffer,d=h.type,u=h.bytesPerElement,p=!0===s.isWebGL2&&(d===t.INT||d===t.UNSIGNED_INT||a.gpuType===XD);if(a.isInterleavedBufferAttribute){const i=a.data,s=i.stride,h=a.offset;if(i.isInstancedInterleavedBuffer){for(let t=0;t<r.locationSize;t++)_(r.location+t,i.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=i.meshPerAttribute*i.count)}else for(let t=0;t<r.locationSize;t++)m(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)v(r.location+t,l/r.locationSize,d,e,s*u,(h+l/r.locationSize*t)*u,p)}else{if(a.isInstancedBufferAttribute){for(let t=0;t<r.locationSize;t++)_(r.location+t,a.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===o._maxInstanceCount&&(o._maxInstanceCount=a.meshPerAttribute*a.count)}else for(let t=0;t<r.locationSize;t++)m(r.location+t);t.bindBuffer(t.ARRAY_BUFFER,c);for(let t=0;t<r.locationSize;t++)v(r.location+t,l/r.locationSize,d,e,l*u,l/r.locationSize*t*u,p)}}else if(void 0!==c){const i=c[e];if(void 0!==i)switch(i.length){case 2:t.vertexAttrib2fv(r.location,i);break;case 3:t.vertexAttrib3fv(r.location,i);break;case 4:t.vertexAttrib4fv(r.location,i);break;default:t.vertexAttrib1fv(r.location,i)}}}}g()}(n,l,u,y),null!==S&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i.get(S).buffer))},reset:y,resetDefaultState:S,dispose:function(){y();for(const t in o){const e=o[t];for(const t in e){const i=e[t];for(const t in i)u(i[t].object),delete i[t];delete e[t]}delete o[t]}},releaseStatesOfGeometry:function(t){if(void 0===o[t.id])return;const e=o[t.id];for(const t in e){const i=e[t];for(const t in i)u(i[t].object),delete i[t];delete e[t]}delete o[t.id]},releaseStatesOfProgram:function(t){for(const e in o){const i=o[e];if(void 0===i[t.id])continue;const s=i[t.id];for(const t in s)u(s[t].object),delete s[t];delete i[t.id]}},initAttributes:f,enableAttribute:m,disableUnusedAttributes:g}}function HF(t,e,i,s){const n=s.isWebGL2;let r;this.setMode=function(t){r=t},this.render=function(e,s){t.drawArrays(r,e,s),i.update(s,r,1)},this.renderInstances=function(s,a,o){if(0===o)return;let l,h;if(n)l=t,h="drawArraysInstanced";else if(l=e.get("ANGLE_instanced_arrays"),h="drawArraysInstancedANGLE",null===l)return;l[h](r,s,a,o),i.update(a,r,o)}}function GF(t,e,i){let s;function n(e){if("highp"===e){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const r="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===t.constructor.name;let a=void 0!==i.precision?i.precision:"highp";const o=n(a);o!==a&&(a=o);const l=r||e.has("WEBGL_draw_buffers"),h=!0===i.logarithmicDepthBuffer,c=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),d=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_TEXTURE_SIZE),p=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),f=t.getParameter(t.MAX_VERTEX_ATTRIBS),m=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),_=t.getParameter(t.MAX_VARYING_VECTORS),g=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),v=d>0,y=r||e.has("OES_texture_float");return{isWebGL2:r,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==s)return s;if(!0===e.has("EXT_texture_filter_anisotropic")){const i=e.get("EXT_texture_filter_anisotropic");s=t.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s},getMaxPrecision:n,precision:a,logarithmicDepthBuffer:h,maxTextures:c,maxVertexTextures:d,maxTextureSize:u,maxCubemapSize:p,maxAttributes:f,maxVertexUniforms:m,maxVaryings:_,maxFragmentUniforms:g,vertexTextures:v,floatFragmentTextures:y,floatVertexTextures:v&&y,maxSamples:r?t.getParameter(t.MAX_SAMPLES):0}}function WF(t){const e=this;let i=null,s=0,n=!1,r=!1;const a=new PF,o=new zI,l={value:null,needsUpdate:!1};function h(t,i,s,n){const r=null!==t?t.length:0;let h=null;if(0!==r){if(h=l.value,!0!==n||null===h){const e=s+4*r,n=i.matrixWorldInverse;o.getNormalMatrix(n),(null===h||h.length<e)&&(h=new Float32Array(e));for(let e=0,i=s;e!==r;++e,i+=4)a.copy(t[e]).applyMatrix4(n,o),a.normal.toArray(h,i),h[i+3]=a.constant}l.value=h,l.needsUpdate=!0}return e.numPlanes=r,e.numIntersection=0,h}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(t,e){const i=0!==t.length||e||0!==s||n;return n=e,s=t.length,i},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(t,e){i=h(t,e,0)},this.setState=function(a,o,c){const d=a.clippingPlanes,u=a.clipIntersection,p=a.clipShadows,f=t.get(a);if(!n||null===d||0===d.length||r&&!p)r?h(null):function(){l.value!==i&&(l.value=i,l.needsUpdate=s>0);e.numPlanes=s,e.numIntersection=0}();else{const t=r?0:s,e=4*t;let n=f.clippingState||null;l.value=n,n=h(d,o,e,c);for(let t=0;t!==e;++t)n[t]=i[t];f.clippingState=n,this.numIntersection=u?this.numPlanes:0,this.numPlanes+=t}}}function XF(t){let e=new WeakMap;function i(t,e){return 303===e?t.mapping=LD:304===e&&(t.mapping=DD),t}function s(t){const i=t.target;i.removeEventListener("dispose",s);const n=e.get(i);void 0!==n&&(e.delete(i),n.dispose())}return{get:function(n){if(n&&n.isTexture&&!1===n.isRenderTargetTexture){const r=n.mapping;if(303===r||304===r){if(e.has(n)){return i(e.get(n).texture,n.mapping)}{const r=n.image;if(r&&r.height>0){const a=new wF(r.height/2);return a.fromEquirectangularTexture(t,n),e.set(n,a),n.addEventListener("dispose",s),i(a.texture,n.mapping)}return null}}}return n},dispose:function(){e=new WeakMap}}}class YF extends SF{constructor(t=-1,e=1,i=1,s=-1,n=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=i,this.bottom=s,this.near=n,this.far=r,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,i,s,n,r){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=s,this.view.width=n,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let n=i-t,r=i+t,a=s+e,o=s-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=t*this.view.offsetX,r=n+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(n,r,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const qF=[.125,.215,.35,.446,.526,.582],jF=20,$F=new YF,KF=new DN;let ZF=null;const QF=(1+Math.sqrt(5))/2,JF=1/QF,tU=[new uO(1,1,1),new uO(-1,1,1),new uO(1,1,-1),new uO(-1,1,-1),new uO(0,QF,JF),new uO(0,QF,-JF),new uO(JF,0,QF),new uO(-JF,0,QF),new uO(QF,JF,0),new uO(-QF,JF,0)];class eU{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,i=.1,s=100){ZF=this._renderer.getRenderTarget(),this._setSize(256);const n=this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(t,i,s,n),e>0&&this._blur(n,0,0,e),this._applyPMREM(n),this._cleanup(n),n}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=rU(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nU(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodPlanes.length;t++)this._lodPlanes[t].dispose()}_cleanup(t){this._renderer.setRenderTarget(ZF),t.scissorTest=!1,sU(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===LD||t.mapping===DD?this._setSize(0===t.image.length?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),ZF=this._renderer.getRenderTarget();const i=e||this._allocateTargets();return this._textureToCubeUV(t,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,i={magFilter:kD,minFilter:kD,generateMipmaps:!1,type:jD,format:KD,colorSpace:oI,depthBuffer:!1},s=iU(t,e,i);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=iU(t,e,i);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(t){const e=[],i=[],s=[];let n=t;const r=t-4+1+qF.length;for(let a=0;a<r;a++){const r=Math.pow(2,n);i.push(r);let o=1/r;a>t-4?o=qF[a-t+4-1]:0===a&&(o=0),s.push(o);const l=1/(r-2),h=-l,c=1+l,d=[h,h,c,h,c,c,h,h,c,c,h,c],u=6,p=6,f=3,m=2,_=1,g=new Float32Array(f*p*u),v=new Float32Array(m*p*u),y=new Float32Array(_*p*u);for(let t=0;t<u;t++){const e=t%3*2/3-1,i=t>2?0:-1,s=[e,i,0,e+2/3,i,0,e+2/3,i+1,0,e,i,0,e+2/3,i+1,0,e,i+1,0];g.set(s,f*p*t),v.set(d,m*p*t);const n=[t,t,t,t,t,t];y.set(n,_*p*t)}const S=new jN;S.setAttribute("position",new UN(g,f)),S.setAttribute("uv",new UN(v,m)),S.setAttribute("faceIndex",new UN(y,_)),e.push(S),n>4&&n--}return{lodPlanes:e,sizeLods:i,sigmas:s}}(s)),this._blurMaterial=function(t,e,i){const s=new Float32Array(jF),n=new uO(0,1,0),r=new yF({name:"SphericalGaussianBlur",defines:{n:jF,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:s},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return r}(s,t,e)}return s}_compileMaterial(t){const e=new uF(this._lodPlanes[0],t);this._renderer.compile(e,$F)}_sceneToCubeUV(t,e,i,s){const n=new xF(90,1,e,i),r=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,h=o.toneMapping;o.getClearColor(KF),o.toneMapping=0,o.autoClear=!1;const c=new ON({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new uF(new fF,c);let u=!1;const p=t.background;p?p.isColor&&(c.color.copy(p),t.background=null,u=!0):(c.color.copy(KF),u=!0);for(let e=0;e<6;e++){const i=e%3;0===i?(n.up.set(0,r[e],0),n.lookAt(a[e],0,0)):1===i?(n.up.set(0,0,r[e]),n.lookAt(0,a[e],0)):(n.up.set(0,r[e],0),n.lookAt(0,0,a[e]));const l=this._cubeSize;sU(s,i*l,e>2?l:0,l,l),o.setRenderTarget(s),u&&o.render(d,n),o.render(t,n)}d.geometry.dispose(),d.material.dispose(),o.toneMapping=h,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const i=this._renderer,s=t.mapping===LD||t.mapping===DD;s?(null===this._cubemapMaterial&&(this._cubemapMaterial=rU()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=nU());const n=s?this._cubemapMaterial:this._equirectMaterial,r=new uF(this._lodPlanes[0],n);n.uniforms.envMap.value=t;const a=this._cubeSize;sU(e,0,0,3*a,2*a),i.setRenderTarget(e),i.render(r,$F)}_applyPMREM(t){const e=this._renderer,i=e.autoClear;e.autoClear=!1;for(let e=1;e<this._lodPlanes.length;e++){const i=Math.sqrt(this._sigmas[e]*this._sigmas[e]-this._sigmas[e-1]*this._sigmas[e-1]),s=tU[(e-1)%tU.length];this._blur(t,e-1,e,i,s)}e.autoClear=i}_blur(t,e,i,s,n){const r=this._pingPongRenderTarget;this._halfBlur(t,r,e,i,s,"latitudinal",n),this._halfBlur(r,t,i,i,s,"longitudinal",n)}_halfBlur(t,e,i,s,n,r,a){const o=this._renderer,l=this._blurMaterial,h=new uF(this._lodPlanes[s],l),c=l.uniforms,d=this._sizeLods[i]-1,u=isFinite(n)?Math.PI/(2*d):2*Math.PI/39,p=n/u,f=isFinite(n)?1+Math.floor(3*p):jF,m=[];let _=0;for(let t=0;t<jF;++t){const e=t/p,i=Math.exp(-e*e/2);m.push(i),0===t?_+=i:t<f&&(_+=2*i)}for(let t=0;t<m.length;t++)m[t]=m[t]/_;c.envMap.value=t.texture,c.samples.value=f,c.weights.value=m,c.latitudinal.value="latitudinal"===r,a&&(c.poleAxis.value=a);const{_lodMax:g}=this;c.dTheta.value=u,c.mipInt.value=g-i;const v=this._sizeLods[s];sU(e,3*v*(s>g-4?s-g+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(e),o.render(h,$F)}}function iU(t,e,i){const s=new lO(t,e,i);return s.texture.mapping=ID,s.texture.name="PMREM.cubeUv",s.scissorTest=!0,s}function sU(t,e,i,s,n){t.viewport.set(e,i,s,n),t.scissor.set(e,i,s,n)}function nU(){return new yF({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function rU(){return new yF({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:aU(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function aU(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function oU(t){let e=new WeakMap,i=null;function s(t){const i=t.target;i.removeEventListener("dispose",s);const n=e.get(i);void 0!==n&&(e.delete(i),n.dispose())}return{get:function(n){if(n&&n.isTexture){const r=n.mapping,a=303===r||304===r,o=r===LD||r===DD;if(a||o){if(n.isRenderTargetTexture&&!0===n.needsPMREMUpdate){n.needsPMREMUpdate=!1;let s=e.get(n);return null===i&&(i=new eU(t)),s=a?i.fromEquirectangular(n,s):i.fromCubemap(n,s),e.set(n,s),s.texture}if(e.has(n))return e.get(n).texture;{const r=n.image;if(a&&r&&r.height>0||o&&r&&function(t){let e=0;const i=6;for(let s=0;s<i;s++)void 0!==t[s]&&e++;return e===i}(r)){null===i&&(i=new eU(t));const r=a?i.fromEquirectangular(n):i.fromCubemap(n);return e.set(n,r),n.addEventListener("dispose",s),r.texture}return null}}}return n},dispose:function(){e=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function lU(t){const e={};function i(i){if(void 0!==e[i])return e[i];let s;switch(i){case"WEBGL_depth_texture":s=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=t.getExtension(i)}return e[i]=s,s}return{has:function(t){return null!==i(t)},init:function(t){t.isWebGL2?i("EXT_color_buffer_float"):(i("WEBGL_depth_texture"),i("OES_texture_float"),i("OES_texture_half_float"),i("OES_texture_half_float_linear"),i("OES_standard_derivatives"),i("OES_element_index_uint"),i("OES_vertex_array_object"),i("ANGLE_instanced_arrays")),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture")},get:function(t){const e=i(t);return e}}}function hU(t,e,i,s){const n={},r=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);for(const t in o.morphAttributes){const i=o.morphAttributes[t];for(let t=0,s=i.length;t<s;t++)e.remove(i[t])}o.removeEventListener("dispose",a),delete n[o.id];const l=r.get(o);l&&(e.remove(l),r.delete(o)),s.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,i.memory.geometries--}function o(t){const i=[],s=t.index,n=t.attributes.position;let a=0;if(null!==s){const t=s.array;a=s.version;for(let e=0,s=t.length;e<s;e+=3){const s=t[e+0],n=t[e+1],r=t[e+2];i.push(s,n,n,r,r,s)}}else{if(void 0===n)return;{const t=n.array;a=n.version;for(let e=0,s=t.length/3-1;e<s;e+=3){const t=e+0,s=e+1,n=e+2;i.push(t,s,s,n,n,t)}}}const o=new(VI(i)?zN:BN)(i,1);o.version=a;const l=r.get(t);l&&e.remove(l),r.set(t,o)}return{get:function(t,e){return!0===n[e.id]||(e.addEventListener("dispose",a),n[e.id]=!0,i.memory.geometries++),e},update:function(i){const s=i.attributes;for(const i in s)e.update(s[i],t.ARRAY_BUFFER);const n=i.morphAttributes;for(const i in n){const s=n[i];for(let i=0,n=s.length;i<n;i++)e.update(s[i],t.ARRAY_BUFFER)}},getWireframeAttribute:function(t){const e=r.get(t);if(e){const i=t.index;null!==i&&e.version<i.version&&o(t)}else o(t);return r.get(t)}}}function cU(t,e,i,s){const n=s.isWebGL2;let r,a,o;this.setMode=function(t){r=t},this.setIndex=function(t){a=t.type,o=t.bytesPerElement},this.render=function(e,s){t.drawElements(r,s,a,e*o),i.update(s,r,1)},this.renderInstances=function(s,l,h){if(0===h)return;let c,d;if(n)c=t,d="drawElementsInstanced";else if(c=e.get("ANGLE_instanced_arrays"),d="drawElementsInstancedANGLE",null===c)return;c[d](r,l,a,s*o,h),i.update(l,r,h)}}function dU(t){const e={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:e,programs:null,autoReset:!0,reset:function(){e.calls=0,e.triangles=0,e.points=0,e.lines=0},update:function(i,s,n){switch(e.calls++,s){case t.TRIANGLES:e.triangles+=n*(i/3);break;case t.LINES:e.lines+=n*(i/2);break;case t.LINE_STRIP:e.lines+=n*(i-1);break;case t.LINE_LOOP:e.lines+=n*i;break;case t.POINTS:e.points+=n*i}}}}function uU(t,e){return t[0]-e[0]}function pU(t,e){return Math.abs(e[1])-Math.abs(t[1])}function fU(t,e,i){const s={},n=new Float32Array(8),r=new WeakMap,a=new aO,o=[];for(let t=0;t<8;t++)o[t]=[t,0];return{update:function(l,h,c){const d=l.morphTargetInfluences;if(!0===e.isWebGL2){const u=h.morphAttributes.position||h.morphAttributes.normal||h.morphAttributes.color,p=void 0!==u?u.length:0;let f=r.get(h);if(void 0===f||f.count!==p){void 0!==f&&f.texture.dispose();const g=void 0!==h.morphAttributes.position,v=void 0!==h.morphAttributes.normal,y=void 0!==h.morphAttributes.color,S=h.morphAttributes.position||[],x=h.morphAttributes.normal||[],T=h.morphAttributes.color||[];let E=0;!0===g&&(E=1),!0===v&&(E=2),!0===y&&(E=3);let b=h.attributes.position.count*E,w=1;b>e.maxTextureSize&&(w=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const A=new Float32Array(b*w*4*p),C=new hO(A,b,w,p);C.type=qD,C.needsUpdate=!0;const M=4*E;for(let R=0;R<p;R++){const L=S[R],D=x[R],I=T[R],O=b*w*4*R;for(let N=0;N<L.count;N++){const F=N*M;!0===g&&(a.fromBufferAttribute(L,N),A[O+F+0]=a.x,A[O+F+1]=a.y,A[O+F+2]=a.z,A[O+F+3]=0),!0===v&&(a.fromBufferAttribute(D,N),A[O+F+4]=a.x,A[O+F+5]=a.y,A[O+F+6]=a.z,A[O+F+7]=0),!0===y&&(a.fromBufferAttribute(I,N),A[O+F+8]=a.x,A[O+F+9]=a.y,A[O+F+10]=a.z,A[O+F+11]=4===I.itemSize?a.w:1)}}function P(){C.dispose(),r.delete(h),h.removeEventListener("dispose",P)}f={count:p,texture:C,size:new BI(b,w)},r.set(h,f),h.addEventListener("dispose",P)}let m=0;for(let U=0;U<d.length;U++)m+=d[U];const _=h.morphTargetsRelative?1:1-m;c.getUniforms().setValue(t,"morphTargetBaseInfluence",_),c.getUniforms().setValue(t,"morphTargetInfluences",d),c.getUniforms().setValue(t,"morphTargetsTexture",f.texture,i),c.getUniforms().setValue(t,"morphTargetsTextureSize",f.size)}else{const B=void 0===d?0:d.length;let z=s[h.id];if(void 0===z||z.length!==B){z=[];for(let W=0;W<B;W++)z[W]=[W,0];s[h.id]=z}for(let X=0;X<B;X++){const Y=z[X];Y[0]=X,Y[1]=d[X]}z.sort(pU);for(let q=0;q<8;q++)q<B&&z[q][1]?(o[q][0]=z[q][0],o[q][1]=z[q][1]):(o[q][0]=Number.MAX_SAFE_INTEGER,o[q][1]=0);o.sort(uU);const k=h.morphAttributes.position,V=h.morphAttributes.normal;let H=0;for(let j=0;j<8;j++){const $=o[j],K=$[0],Z=$[1];K!==Number.MAX_SAFE_INTEGER&&Z?(k&&h.getAttribute("morphTarget"+j)!==k[K]&&h.setAttribute("morphTarget"+j,k[K]),V&&h.getAttribute("morphNormal"+j)!==V[K]&&h.setAttribute("morphNormal"+j,V[K]),n[j]=Z,H+=Z):(k&&!0===h.hasAttribute("morphTarget"+j)&&h.deleteAttribute("morphTarget"+j),V&&!0===h.hasAttribute("morphNormal"+j)&&h.deleteAttribute("morphNormal"+j),n[j]=0)}const G=h.morphTargetsRelative?1:1-H;c.getUniforms().setValue(t,"morphTargetBaseInfluence",G),c.getUniforms().setValue(t,"morphTargetInfluences",n)}}}}function mU(t,e,i,s){let n=new WeakMap;function r(t){const e=t.target;e.removeEventListener("dispose",r),i.remove(e.instanceMatrix),null!==e.instanceColor&&i.remove(e.instanceColor)}return{update:function(a){const o=s.render.frame,l=a.geometry,h=e.get(a,l);if(n.get(h)!==o&&(e.update(h),n.set(h,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",r)&&a.addEventListener("dispose",r),n.get(a)!==o&&(i.update(a.instanceMatrix,t.ARRAY_BUFFER),null!==a.instanceColor&&i.update(a.instanceColor,t.ARRAY_BUFFER),n.set(a,o))),a.isSkinnedMesh){const t=a.skeleton;n.get(t)!==o&&(t.update(),n.set(t,o))}return h},dispose:function(){n=new WeakMap}}}const _U=new rO,gU=new hO,vU=new cO,yU=new bF,SU=[],xU=[],TU=new Float32Array(16),EU=new Float32Array(9),bU=new Float32Array(4);function wU(t,e,i){const s=t[0];if(s<=0||s>0)return t;const n=e*i;let r=SU[n];if(void 0===r&&(r=new Float32Array(n),SU[n]=r),0!==e){s.toArray(r,0);for(let s=1,n=0;s!==e;++s)n+=i,t[s].toArray(r,n)}return r}function AU(t,e){if(t.length!==e.length)return!1;for(let i=0,s=t.length;i<s;i++)if(t[i]!==e[i])return!1;return!0}function CU(t,e){for(let i=0,s=e.length;i<s;i++)t[i]=e[i]}function MU(t,e){let i=xU[e];void 0===i&&(i=new Int32Array(e),xU[e]=i);for(let s=0;s!==e;++s)i[s]=t.allocateTextureUnit();return i}function PU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1f(this.addr,e),i[0]=e)}function RU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2f(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2fv(this.addr,e),CU(i,e)}}function LU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3f(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else if(void 0!==e.r)i[0]===e.r&&i[1]===e.g&&i[2]===e.b||(t.uniform3f(this.addr,e.r,e.g,e.b),i[0]=e.r,i[1]=e.g,i[2]=e.b);else{if(AU(i,e))return;t.uniform3fv(this.addr,e),CU(i,e)}}function DU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4fv(this.addr,e),CU(i,e)}}function IU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix2fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;bU.set(s),t.uniformMatrix2fv(this.addr,!1,bU),CU(i,s)}}function OU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix3fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;EU.set(s),t.uniformMatrix3fv(this.addr,!1,EU),CU(i,s)}}function NU(t,e){const i=this.cache,s=e.elements;if(void 0===s){if(AU(i,e))return;t.uniformMatrix4fv(this.addr,!1,e),CU(i,e)}else{if(AU(i,s))return;TU.set(s),t.uniformMatrix4fv(this.addr,!1,TU),CU(i,s)}}function FU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1i(this.addr,e),i[0]=e)}function UU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2i(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2iv(this.addr,e),CU(i,e)}}function BU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3i(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else{if(AU(i,e))return;t.uniform3iv(this.addr,e),CU(i,e)}}function zU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4i(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4iv(this.addr,e),CU(i,e)}}function kU(t,e){const i=this.cache;i[0]!==e&&(t.uniform1ui(this.addr,e),i[0]=e)}function VU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y||(t.uniform2ui(this.addr,e.x,e.y),i[0]=e.x,i[1]=e.y);else{if(AU(i,e))return;t.uniform2uiv(this.addr,e),CU(i,e)}}function HU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z||(t.uniform3ui(this.addr,e.x,e.y,e.z),i[0]=e.x,i[1]=e.y,i[2]=e.z);else{if(AU(i,e))return;t.uniform3uiv(this.addr,e),CU(i,e)}}function GU(t,e){const i=this.cache;if(void 0!==e.x)i[0]===e.x&&i[1]===e.y&&i[2]===e.z&&i[3]===e.w||(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),i[0]=e.x,i[1]=e.y,i[2]=e.z,i[3]=e.w);else{if(AU(i,e))return;t.uniform4uiv(this.addr,e),CU(i,e)}}function WU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture2D(e||_U,n)}function XU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture3D(e||vU,n)}function YU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTextureCube(e||yU,n)}function qU(t,e,i){const s=this.cache,n=i.allocateTextureUnit();s[0]!==n&&(t.uniform1i(this.addr,n),s[0]=n),i.setTexture2DArray(e||gU,n)}function jU(t,e){t.uniform1fv(this.addr,e)}function $U(t,e){const i=wU(e,this.size,2);t.uniform2fv(this.addr,i)}function KU(t,e){const i=wU(e,this.size,3);t.uniform3fv(this.addr,i)}function ZU(t,e){const i=wU(e,this.size,4);t.uniform4fv(this.addr,i)}function QU(t,e){const i=wU(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,i)}function JU(t,e){const i=wU(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,i)}function tB(t,e){const i=wU(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,i)}function eB(t,e){t.uniform1iv(this.addr,e)}function iB(t,e){t.uniform2iv(this.addr,e)}function sB(t,e){t.uniform3iv(this.addr,e)}function nB(t,e){t.uniform4iv(this.addr,e)}function rB(t,e){t.uniform1uiv(this.addr,e)}function aB(t,e){t.uniform2uiv(this.addr,e)}function oB(t,e){t.uniform3uiv(this.addr,e)}function lB(t,e){t.uniform4uiv(this.addr,e)}function hB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture2D(e[t]||_U,r[t])}function cB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture3D(e[t]||vU,r[t])}function dB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTextureCube(e[t]||yU,r[t])}function uB(t,e,i){const s=this.cache,n=e.length,r=MU(i,n);AU(s,r)||(t.uniform1iv(this.addr,r),CU(s,r));for(let t=0;t!==n;++t)i.setTexture2DArray(e[t]||gU,r[t])}class pB{constructor(t,e,i){this.id=t,this.addr=i,this.cache=[],this.setValue=function(t){switch(t){case 5126:return PU;case 35664:return RU;case 35665:return LU;case 35666:return DU;case 35674:return IU;case 35675:return OU;case 35676:return NU;case 5124:case 35670:return FU;case 35667:case 35671:return UU;case 35668:case 35672:return BU;case 35669:case 35673:return zU;case 5125:return kU;case 36294:return VU;case 36295:return HU;case 36296:return GU;case 35678:case 36198:case 36298:case 36306:case 35682:return WU;case 35679:case 36299:case 36307:return XU;case 35680:case 36300:case 36308:case 36293:return YU;case 36289:case 36303:case 36311:case 36292:return qU}}(e.type)}}class fB{constructor(t,e,i){this.id=t,this.addr=i,this.cache=[],this.size=e.size,this.setValue=function(t){switch(t){case 5126:return jU;case 35664:return $U;case 35665:return KU;case 35666:return ZU;case 35674:return QU;case 35675:return JU;case 35676:return tB;case 5124:case 35670:return eB;case 35667:case 35671:return iB;case 35668:case 35672:return sB;case 35669:case 35673:return nB;case 5125:return rB;case 36294:return aB;case 36295:return oB;case 36296:return lB;case 35678:case 36198:case 36298:case 36306:case 35682:return hB;case 35679:case 36299:case 36307:return cB;case 35680:case 36300:case 36308:case 36293:return dB;case 36289:case 36303:case 36311:case 36292:return uB}}(e.type)}}class mB{constructor(t){this.id=t,this.seq=[],this.map={}}setValue(t,e,i){const s=this.seq;for(let n=0,r=s.length;n!==r;++n){const r=s[n];r.setValue(t,e[r.id],i)}}}const _B=/(\w+)(\])?(\[|\.)?/g;function gB(t,e){t.seq.push(e),t.map[e.id]=e}function vB(t,e,i){const s=t.name,n=s.length;for(_B.lastIndex=0;;){const r=_B.exec(s),a=_B.lastIndex;let o=r[1];const l="]"===r[2],h=r[3];if(l&&(o|=0),void 0===h||"["===h&&a+2===n){gB(i,void 0===h?new pB(o,t,e):new fB(o,t,e));break}{let t=i.map[o];void 0===t&&(t=new mB(o),gB(i,t)),i=t}}}class yB{constructor(t,e){this.seq=[],this.map={};const i=t.getProgramParameter(e,t.ACTIVE_UNIFORMS);for(let s=0;s<i;++s){const i=t.getActiveUniform(e,s);vB(i,t.getUniformLocation(e,i.name),this)}}setValue(t,e,i,s){const n=this.map[e];void 0!==n&&n.setValue(t,i,s)}setOptional(t,e,i){const s=e[i];void 0!==s&&this.setValue(t,i,s)}static upload(t,e,i,s){for(let n=0,r=e.length;n!==r;++n){const r=e[n],a=i[r.id];!1!==a.needsUpdate&&r.setValue(t,a.value,s)}}static seqWithValue(t,e){const i=[];for(let s=0,n=t.length;s!==n;++s){const n=t[s];n.id in e&&i.push(n)}return i}}function SB(t,e,i){const s=t.createShader(e);return t.shaderSource(s,i),t.compileShader(s),s}let xB=0;function TB(t,e,i){const s=t.getShaderParameter(e,t.COMPILE_STATUS),n=t.getShaderInfoLog(e).trim();if(s&&""===n)return"";const r=/ERROR: 0:(\d+)/.exec(n);if(r){const s=parseInt(r[1]);return i.toUpperCase()+"\n\n"+n+"\n\n"+function(t,e){const i=t.split("\n"),s=[],n=Math.max(e-6,0),r=Math.min(e+6,i.length);for(let t=n;t<r;t++){const n=t+1;s.push(`${n===e?">":" "} ${n}: ${i[t]}`)}return s.join("\n")}(t.getShaderSource(e),s)}return n}function EB(t,e){const i=function(t){const e=KI.getPrimaries(KI.workingColorSpace),i=KI.getPrimaries(t);let s;switch(e===i?s="":e===pI&&i===uI?s="LinearDisplayP3ToLinearSRGB":e===uI&&i===pI&&(s="LinearSRGBToLinearDisplayP3"),t){case oI:case hI:return[s,"LinearTransferOETF"];case aI:case lI:return[s,"sRGBTransferOETF"];default:return[s,"LinearTransferOETF"]}}(e);return`vec4 ${t}( vec4 value ) { return ${i[0]}( ${i[1]}( value ) ); }`}function bB(t,e){let i;switch(e){case 1:default:i="Linear";break;case 2:i="Reinhard";break;case 3:i="OptimizedCineon";break;case 4:i="ACESFilmic";break;case 5:i="Custom"}return"vec3 "+t+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}function wB(t){return""!==t}function AB(t,e){const i=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,i).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function CB(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const MB=/^[ \t]*#include +<([\w\d./]+)>/gm;function PB(t){return t.replace(MB,LB)}const RB=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function LB(t,e){let i=FF[e];if(void 0===i){const t=RB.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");i=FF[t]}return PB(i)}const DB=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function IB(t){return t.replace(DB,OB)}function OB(t,e,i,s){let n="";for(let t=parseInt(e);t<parseInt(i);t++)n+=s.replace(/\[\s*i\s*\]/g,"[ "+t+" ]").replace(/UNROLLED_LOOP_INDEX/g,t);return n}function NB(t){let e="precision "+t.precision+" float;\nprecision "+t.precision+" int;";return"highp"===t.precision?e+="\n#define HIGH_PRECISION":"mediump"===t.precision?e+="\n#define MEDIUM_PRECISION":"lowp"===t.precision&&(e+="\n#define LOW_PRECISION"),e}function FB(t,e,i,s){const n=t.getContext(),r=i.defines;let a=i.vertexShader,o=i.fragmentShader;const l=function(t){let e="SHADOWMAP_TYPE_BASIC";return 1===t.shadowMapType?e="SHADOWMAP_TYPE_PCF":2===t.shadowMapType?e="SHADOWMAP_TYPE_PCF_SOFT":3===t.shadowMapType&&(e="SHADOWMAP_TYPE_VSM"),e}(i),h=function(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case LD:case DD:e="ENVMAP_TYPE_CUBE";break;case ID:e="ENVMAP_TYPE_CUBE_UV"}return e}(i),c=function(t){let e="ENVMAP_MODE_REFLECTION";t.envMap&&t.envMapMode===DD&&(e="ENVMAP_MODE_REFRACTION");return e}(i),d=function(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case 0:e="ENVMAP_BLENDING_MULTIPLY";break;case 1:e="ENVMAP_BLENDING_MIX";break;case 2:e="ENVMAP_BLENDING_ADD"}return e}(i),u=function(t){const e=t.envMapCubeUVHeight;if(null===e)return null;const i=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,i),112)),texelHeight:s,maxMip:i}}(i),p=i.isWebGL2?"":function(t){return[t.extensionDerivatives||t.envMapCubeUVHeight||t.bumpMap||t.normalMapTangentSpace||t.clearcoatNormalMap||t.flatShading||"physical"===t.shaderID?"#extension GL_OES_standard_derivatives : enable":"",(t.extensionFragDepth||t.logarithmicDepthBuffer)&&t.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",t.extensionDrawBuffers&&t.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(t.extensionShaderTextureLOD||t.envMap||t.transmission)&&t.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(wB).join("\n")}(i),f=function(t){const e=[];for(const i in t){const s=t[i];!1!==s&&e.push("#define "+i+" "+s)}return e.join("\n")}(r),m=n.createProgram();let _,g,v=i.glslVersion?"#version "+i.glslVersion+"\n":"";i.isRawShaderMaterial?(_=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f].filter(wB).join("\n"),_.length>0&&(_+="\n"),g=[p,"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f].filter(wB).join("\n"),g.length>0&&(g+="\n")):(_=[NB(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f,i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+c:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&!1===i.flatShading?"#define USE_MORPHNORMALS":"",i.morphColors&&i.isWebGL2?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0&&i.isWebGL2?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.useLegacyLights?"#define LEGACY_LIGHTS":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(wB).join("\n"),g=[p,NB(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,f,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+h:"",i.envMap?"#define "+c:"",i.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.useLegacyLights?"#define LEGACY_LIGHTS":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",i.logarithmicDepthBuffer&&i.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==i.toneMapping?"#define TONE_MAPPING":"",0!==i.toneMapping?FF.tonemapping_pars_fragment:"",0!==i.toneMapping?bB("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",FF.colorspace_pars_fragment,EB("linearToOutputTexel",i.outputColorSpace),i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(wB).join("\n")),a=PB(a),a=AB(a,i),a=CB(a,i),o=PB(o),o=AB(o,i),o=CB(o,i),a=IB(a),o=IB(o),i.isWebGL2&&!0!==i.isRawShaderMaterial&&(v="#version 300 es\n",_=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+_,g=["#define varying in",i.glslVersion===EI?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===EI?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+g);const y=v+_+a,S=v+g+o,x=SB(n,n.VERTEX_SHADER,y),T=SB(n,n.FRAGMENT_SHADER,S);if(n.attachShader(m,x),n.attachShader(m,T),void 0!==i.index0AttributeName?n.bindAttribLocation(m,0,i.index0AttributeName):!0===i.morphTargets&&n.bindAttribLocation(m,0,"position"),n.linkProgram(m),t.debug.checkShaderErrors){const e=n.getProgramInfoLog(m).trim(),i=n.getShaderInfoLog(x).trim(),s=n.getShaderInfoLog(T).trim();let r=!0,a=!0;if(!1===n.getProgramParameter(m,n.LINK_STATUS))if(r=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(n,m,x,T);else{TB(n,x,"vertex"),TB(n,T,"fragment")}else""!==e||""!==i&&""!==s||(a=!1);a&&(this.diagnostics={runnable:r,programLog:e,vertexShader:{log:i,prefix:_},fragmentShader:{log:s,prefix:g}})}let E,b;return n.deleteShader(x),n.deleteShader(T),this.getUniforms=function(){return void 0===E&&(E=new yB(n,m)),E},this.getAttributes=function(){return void 0===b&&(b=function(t,e){const i={},s=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let n=0;n<s;n++){const s=t.getActiveAttrib(e,n),r=s.name;let a=1;s.type===t.FLOAT_MAT2&&(a=2),s.type===t.FLOAT_MAT3&&(a=3),s.type===t.FLOAT_MAT4&&(a=4),i[r]={type:s.type,location:t.getAttribLocation(e,r),locationSize:a}}return i}(n,m)),b},this.destroy=function(){s.releaseStatesOfProgram(this),n.deleteProgram(m),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=xB++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=x,this.fragmentShader=T,this}let UB=0;class BB{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){const e=t.vertexShader,i=t.fragmentShader,s=this._getShaderStage(e),n=this._getShaderStage(i),r=this._getShaderCacheForMaterial(t);return!1===r.has(s)&&(r.add(s),s.usedTimes++),!1===r.has(n)&&(r.add(n),n.usedTimes++),this}remove(t){const e=this.materialCache.get(t);for(const t of e)t.usedTimes--,0===t.usedTimes&&this.shaderCache.delete(t.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){const e=this.materialCache;let i=e.get(t);return void 0===i&&(i=new Set,e.set(t,i)),i}_getShaderStage(t){const e=this.shaderCache;let i=e.get(t);return void 0===i&&(i=new zB(t),e.set(t,i)),i}}class zB{constructor(t){this.id=UB++,this.code=t,this.usedTimes=0}}function kB(t,e,i,s,n,r,a){const o=new JO,l=new BB,h=[],c=n.isWebGL2,d=n.logarithmicDepthBuffer,u=n.vertexTextures;let p=n.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(t){return 0===t?"uv":`uv${t}`}return{getParameters:function(r,o,h,_,g){const v=_.fog,y=g.geometry,S=r.isMeshStandardMaterial?_.environment:null,x=(r.isMeshStandardMaterial?i:e).get(r.envMap||S),T=x&&x.mapping===ID?x.image.height:null,E=f[r.type];null!==r.precision&&(p=n.getMaxPrecision(r.precision),r.precision);const b=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,w=void 0!==b?b.length:0;let A,C,M,P,R=0;if(void 0!==y.morphAttributes.position&&(R=1),void 0!==y.morphAttributes.normal&&(R=2),void 0!==y.morphAttributes.color&&(R=3),E){const t=BF[E];A=t.vertexShader,C=t.fragmentShader}else A=r.vertexShader,C=r.fragmentShader,l.update(r),M=l.getVertexShaderID(r),P=l.getFragmentShaderID(r);const L=t.getRenderTarget(),D=!0===g.isInstancedMesh,I=!!r.map,O=!!r.matcap,N=!!x,F=!!r.aoMap,U=!!r.lightMap,B=!!r.bumpMap,z=!!r.normalMap,k=!!r.displacementMap,V=!!r.emissiveMap,H=!!r.metalnessMap,G=!!r.roughnessMap,W=r.anisotropy>0,X=r.clearcoat>0,Y=r.iridescence>0,q=r.sheen>0,j=r.transmission>0,$=W&&!!r.anisotropyMap,K=X&&!!r.clearcoatMap,Z=X&&!!r.clearcoatNormalMap,Q=X&&!!r.clearcoatRoughnessMap,J=Y&&!!r.iridescenceMap,tt=Y&&!!r.iridescenceThicknessMap,et=q&&!!r.sheenColorMap,it=q&&!!r.sheenRoughnessMap,st=!!r.specularMap,nt=!!r.specularColorMap,rt=!!r.specularIntensityMap,at=j&&!!r.transmissionMap,ot=j&&!!r.thicknessMap,lt=!!r.gradientMap,ht=!!r.alphaMap,ct=r.alphaTest>0,dt=!!r.alphaHash,ut=!!r.extensions,pt=!!y.attributes.uv1,ft=!!y.attributes.uv2,mt=!!y.attributes.uv3;let _t=0;return r.toneMapped&&(null!==L&&!0!==L.isXRRenderTarget||(_t=t.toneMapping)),{isWebGL2:c,shaderID:E,shaderType:r.type,shaderName:r.name,vertexShader:A,fragmentShader:C,defines:r.defines,customVertexShaderID:M,customFragmentShaderID:P,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:p,instancing:D,instancingColor:D&&null!==g.instanceColor,supportsVertexTextures:u,outputColorSpace:null===L?t.outputColorSpace:!0===L.isXRRenderTarget?L.texture.colorSpace:oI,map:I,matcap:O,envMap:N,envMapMode:N&&x.mapping,envMapCubeUVHeight:T,aoMap:F,lightMap:U,bumpMap:B,normalMap:z,displacementMap:u&&k,emissiveMap:V,normalMapObjectSpace:z&&1===r.normalMapType,normalMapTangentSpace:z&&0===r.normalMapType,metalnessMap:H,roughnessMap:G,anisotropy:W,anisotropyMap:$,clearcoat:X,clearcoatMap:K,clearcoatNormalMap:Z,clearcoatRoughnessMap:Q,iridescence:Y,iridescenceMap:J,iridescenceThicknessMap:tt,sheen:q,sheenColorMap:et,sheenRoughnessMap:it,specularMap:st,specularColorMap:nt,specularIntensityMap:rt,transmission:j,transmissionMap:at,thicknessMap:ot,gradientMap:lt,opaque:!1===r.transparent&&1===r.blending,alphaMap:ht,alphaTest:ct,alphaHash:dt,combine:r.combine,mapUv:I&&m(r.map.channel),aoMapUv:F&&m(r.aoMap.channel),lightMapUv:U&&m(r.lightMap.channel),bumpMapUv:B&&m(r.bumpMap.channel),normalMapUv:z&&m(r.normalMap.channel),displacementMapUv:k&&m(r.displacementMap.channel),emissiveMapUv:V&&m(r.emissiveMap.channel),metalnessMapUv:H&&m(r.metalnessMap.channel),roughnessMapUv:G&&m(r.roughnessMap.channel),anisotropyMapUv:$&&m(r.anisotropyMap.channel),clearcoatMapUv:K&&m(r.clearcoatMap.channel),clearcoatNormalMapUv:Z&&m(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Q&&m(r.clearcoatRoughnessMap.channel),iridescenceMapUv:J&&m(r.iridescenceMap.channel),iridescenceThicknessMapUv:tt&&m(r.iridescenceThicknessMap.channel),sheenColorMapUv:et&&m(r.sheenColorMap.channel),sheenRoughnessMapUv:it&&m(r.sheenRoughnessMap.channel),specularMapUv:st&&m(r.specularMap.channel),specularColorMapUv:nt&&m(r.specularColorMap.channel),specularIntensityMapUv:rt&&m(r.specularIntensityMap.channel),transmissionMapUv:at&&m(r.transmissionMap.channel),thicknessMapUv:ot&&m(r.thicknessMap.channel),alphaMapUv:ht&&m(r.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(z||W),vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,vertexUv1s:pt,vertexUv2s:ft,vertexUv3s:mt,pointsUvs:!0===g.isPoints&&!!y.attributes.uv&&(I||ht),fog:!!v,useFog:!0===r.fog,fogExp2:v&&v.isFogExp2,flatShading:!0===r.flatShading,sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:d,skinning:!0===g.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:w,morphTextureStride:R,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:r.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:_t,useLegacyLights:t._useLegacyLights,decodeVideoTexture:I&&!0===r.map.isVideoTexture&&KI.getTransfer(r.map.colorSpace)===dI,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionDerivatives:ut&&!0===r.extensions.derivatives,extensionFragDepth:ut&&!0===r.extensions.fragDepth,extensionDrawBuffers:ut&&!0===r.extensions.drawBuffers,extensionShaderTextureLOD:ut&&!0===r.extensions.shaderTextureLOD,rendererExtensionFragDepth:c||s.has("EXT_frag_depth"),rendererExtensionDrawBuffers:c||s.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:c||s.has("EXT_shader_texture_lod"),customProgramCacheKey:r.customProgramCacheKey()}},getProgramCacheKey:function(e){const i=[];if(e.shaderID?i.push(e.shaderID):(i.push(e.customVertexShaderID),i.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)i.push(t),i.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(i,e),function(t,e){o.disableAll(),e.isWebGL2&&o.enable(0);e.supportsVertexTextures&&o.enable(1);e.instancing&&o.enable(2);e.instancingColor&&o.enable(3);e.matcap&&o.enable(4);e.envMap&&o.enable(5);e.normalMapObjectSpace&&o.enable(6);e.normalMapTangentSpace&&o.enable(7);e.clearcoat&&o.enable(8);e.iridescence&&o.enable(9);e.alphaTest&&o.enable(10);e.vertexColors&&o.enable(11);e.vertexAlphas&&o.enable(12);e.vertexUv1s&&o.enable(13);e.vertexUv2s&&o.enable(14);e.vertexUv3s&&o.enable(15);e.vertexTangents&&o.enable(16);e.anisotropy&&o.enable(17);t.push(o.mask),o.disableAll(),e.fog&&o.enable(0);e.useFog&&o.enable(1);e.flatShading&&o.enable(2);e.logarithmicDepthBuffer&&o.enable(3);e.skinning&&o.enable(4);e.morphTargets&&o.enable(5);e.morphNormals&&o.enable(6);e.morphColors&&o.enable(7);e.premultipliedAlpha&&o.enable(8);e.shadowMapEnabled&&o.enable(9);e.useLegacyLights&&o.enable(10);e.doubleSided&&o.enable(11);e.flipSided&&o.enable(12);e.useDepthPacking&&o.enable(13);e.dithering&&o.enable(14);e.transmission&&o.enable(15);e.sheen&&o.enable(16);e.opaque&&o.enable(17);e.pointsUvs&&o.enable(18);e.decodeVideoTexture&&o.enable(19);t.push(o.mask)}(i,e),i.push(t.outputColorSpace)),i.push(e.customProgramCacheKey),i.join()},getUniforms:function(t){const e=f[t.type];let i;if(e){const t=BF[e];i=vF.clone(t.uniforms)}else i=t.uniforms;return i},acquireProgram:function(e,i){let s;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(e.cacheKey===i){s=e,++s.usedTimes;break}}return void 0===s&&(s=new FB(t,i,e,r),h.push(s)),s},releaseProgram:function(t){if(0===--t.usedTimes){const e=h.indexOf(t);h[e]=h[h.length-1],h.pop(),t.destroy()}},releaseShaderCache:function(t){l.remove(t)},programs:h,dispose:function(){l.dispose()}}}function VB(){let t=new WeakMap;return{get:function(e){let i=t.get(e);return void 0===i&&(i={},t.set(e,i)),i},remove:function(e){t.delete(e)},update:function(e,i,s){t.get(e)[i]=s},dispose:function(){t=new WeakMap}}}function HB(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function GB(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function WB(){const t=[];let e=0;const i=[],s=[],n=[];function r(i,s,n,r,a,o){let l=t[e];return void 0===l?(l={id:i.id,object:i,geometry:s,material:n,groupOrder:r,renderOrder:i.renderOrder,z:a,group:o},t[e]=l):(l.id=i.id,l.object=i,l.geometry=s,l.material=n,l.groupOrder=r,l.renderOrder=i.renderOrder,l.z=a,l.group=o),e++,l}return{opaque:i,transmissive:s,transparent:n,init:function(){e=0,i.length=0,s.length=0,n.length=0},push:function(t,e,a,o,l,h){const c=r(t,e,a,o,l,h);a.transmission>0?s.push(c):!0===a.transparent?n.push(c):i.push(c)},unshift:function(t,e,a,o,l,h){const c=r(t,e,a,o,l,h);a.transmission>0?s.unshift(c):!0===a.transparent?n.unshift(c):i.unshift(c)},finish:function(){for(let i=e,s=t.length;i<s;i++){const e=t[i];if(null===e.id)break;e.id=null,e.object=null,e.geometry=null,e.material=null,e.group=null}},sort:function(t,e){i.length>1&&i.sort(t||HB),s.length>1&&s.sort(e||GB),n.length>1&&n.sort(e||GB)}}}function XB(){let t=new WeakMap;return{get:function(e,i){const s=t.get(e);let n;return void 0===s?(n=new WB,t.set(e,[n])):i>=s.length?(n=new WB,s.push(n)):n=s[i],n},dispose:function(){t=new WeakMap}}}function YB(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":i={direction:new uO,color:new DN};break;case"SpotLight":i={position:new uO,direction:new uO,color:new DN,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new uO,color:new DN,distance:0,decay:0};break;case"HemisphereLight":i={direction:new uO,skyColor:new DN,groundColor:new DN};break;case"RectAreaLight":i={color:new DN,position:new uO,halfWidth:new uO,halfHeight:new uO}}return t[e.id]=i,i}}}let qB=0;function jB(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function $B(t,e){const i=new YB,s=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let i;switch(e.type){case"DirectionalLight":case"SpotLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new BI};break;case"PointLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new BI,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=i,i}}}(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let t=0;t<9;t++)n.probe.push(new uO);const r=new uO,a=new HO,o=new HO;return{setup:function(r,a){let o=0,l=0,h=0;for(let t=0;t<9;t++)n.probe[t].set(0,0,0);let c=0,d=0,u=0,p=0,f=0,m=0,_=0,g=0,v=0,y=0,S=0;r.sort(jB);const x=!0===a?Math.PI:1;for(let t=0,e=r.length;t<e;t++){const e=r[t],a=e.color,T=e.intensity,E=e.distance,b=e.shadow&&e.shadow.map?e.shadow.map.texture:null;if(e.isAmbientLight)o+=a.r*T*x,l+=a.g*T*x,h+=a.b*T*x;else if(e.isLightProbe){for(let t=0;t<9;t++)n.probe[t].addScaledVector(e.sh.coefficients[t],T);S++}else if(e.isDirectionalLight){const t=i.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*x),e.castShadow){const t=e.shadow,i=s.get(e);i.shadowBias=t.bias,i.shadowNormalBias=t.normalBias,i.shadowRadius=t.radius,i.shadowMapSize=t.mapSize,n.directionalShadow[c]=i,n.directionalShadowMap[c]=b,n.directionalShadowMatrix[c]=e.shadow.matrix,m++}n.directional[c]=t,c++}else if(e.isSpotLight){const t=i.get(e);t.position.setFromMatrixPosition(e.matrixWorld),t.color.copy(a).multiplyScalar(T*x),t.distance=E,t.coneCos=Math.cos(e.angle),t.penumbraCos=Math.cos(e.angle*(1-e.penumbra)),t.decay=e.decay,n.spot[u]=t;const r=e.shadow;if(e.map&&(n.spotLightMap[v]=e.map,v++,r.updateMatrices(e),e.castShadow&&y++),n.spotLightMatrix[u]=r.matrix,e.castShadow){const t=s.get(e);t.shadowBias=r.bias,t.shadowNormalBias=r.normalBias,t.shadowRadius=r.radius,t.shadowMapSize=r.mapSize,n.spotShadow[u]=t,n.spotShadowMap[u]=b,g++}u++}else if(e.isRectAreaLight){const t=i.get(e);t.color.copy(a).multiplyScalar(T),t.halfWidth.set(.5*e.width,0,0),t.halfHeight.set(0,.5*e.height,0),n.rectArea[p]=t,p++}else if(e.isPointLight){const t=i.get(e);if(t.color.copy(e.color).multiplyScalar(e.intensity*x),t.distance=e.distance,t.decay=e.decay,e.castShadow){const t=e.shadow,i=s.get(e);i.shadowBias=t.bias,i.shadowNormalBias=t.normalBias,i.shadowRadius=t.radius,i.shadowMapSize=t.mapSize,i.shadowCameraNear=t.camera.near,i.shadowCameraFar=t.camera.far,n.pointShadow[d]=i,n.pointShadowMap[d]=b,n.pointShadowMatrix[d]=e.shadow.matrix,_++}n.point[d]=t,d++}else if(e.isHemisphereLight){const t=i.get(e);t.skyColor.copy(e.color).multiplyScalar(T*x),t.groundColor.copy(e.groundColor).multiplyScalar(T*x),n.hemi[f]=t,f++}}p>0&&(e.isWebGL2||!0===t.has("OES_texture_float_linear")?(n.rectAreaLTC1=UF.LTC_FLOAT_1,n.rectAreaLTC2=UF.LTC_FLOAT_2):!0===t.has("OES_texture_half_float_linear")&&(n.rectAreaLTC1=UF.LTC_HALF_1,n.rectAreaLTC2=UF.LTC_HALF_2)),n.ambient[0]=o,n.ambient[1]=l,n.ambient[2]=h;const T=n.hash;T.directionalLength===c&&T.pointLength===d&&T.spotLength===u&&T.rectAreaLength===p&&T.hemiLength===f&&T.numDirectionalShadows===m&&T.numPointShadows===_&&T.numSpotShadows===g&&T.numSpotMaps===v&&T.numLightProbes===S||(n.directional.length=c,n.spot.length=u,n.rectArea.length=p,n.point.length=d,n.hemi.length=f,n.directionalShadow.length=m,n.directionalShadowMap.length=m,n.pointShadow.length=_,n.pointShadowMap.length=_,n.spotShadow.length=g,n.spotShadowMap.length=g,n.directionalShadowMatrix.length=m,n.pointShadowMatrix.length=_,n.spotLightMatrix.length=g+v-y,n.spotLightMap.length=v,n.numSpotLightShadowsWithMaps=y,n.numLightProbes=S,T.directionalLength=c,T.pointLength=d,T.spotLength=u,T.rectAreaLength=p,T.hemiLength=f,T.numDirectionalShadows=m,T.numPointShadows=_,T.numSpotShadows=g,T.numSpotMaps=v,T.numLightProbes=S,n.version=qB++)},setupView:function(t,e){let i=0,s=0,l=0,h=0,c=0;const d=e.matrixWorldInverse;for(let e=0,u=t.length;e<u;e++){const u=t[e];if(u.isDirectionalLight){const t=n.directional[i];t.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(d),i++}else if(u.isSpotLight){const t=n.spot[l];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),t.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),t.direction.sub(r),t.direction.transformDirection(d),l++}else if(u.isRectAreaLight){const t=n.rectArea[h];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),o.identity(),a.copy(u.matrixWorld),a.premultiply(d),o.extractRotation(a),t.halfWidth.set(.5*u.width,0,0),t.halfHeight.set(0,.5*u.height,0),t.halfWidth.applyMatrix4(o),t.halfHeight.applyMatrix4(o),h++}else if(u.isPointLight){const t=n.point[s];t.position.setFromMatrixPosition(u.matrixWorld),t.position.applyMatrix4(d),s++}else if(u.isHemisphereLight){const t=n.hemi[c];t.direction.setFromMatrixPosition(u.matrixWorld),t.direction.transformDirection(d),c++}}},state:n}}function KB(t,e){const i=new $B(t,e),s=[],n=[];return{init:function(){s.length=0,n.length=0},state:{lightsArray:s,shadowsArray:n,lights:i},setupLights:function(t){i.setup(s,t)},setupLightsView:function(t){i.setupView(s,t)},pushLight:function(t){s.push(t)},pushShadow:function(t){n.push(t)}}}function ZB(t,e){let i=new WeakMap;return{get:function(s,n=0){const r=i.get(s);let a;return void 0===r?(a=new KB(t,e),i.set(s,[a])):n>=r.length?(a=new KB(t,e),r.push(a)):a=r[n],a},dispose:function(){i=new WeakMap}}}class QB extends CN{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class JB extends CN{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function tz(t,e,i){let s=new DF;const n=new BI,r=new BI,a=new aO,o=new QB({depthPacking:3201}),l=new JB,h={},c=i.maxTextureSize,d={[fD]:1,[mD]:0,[_D]:2},u=new yF({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new BI},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=u.clone();p.defines.HORIZONTAL_PASS=1;const f=new jN;f.setAttribute("position",new UN(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new uF(f,u),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let g=this.type;function v(i,s){const r=e.update(m);u.defines.VSM_SAMPLES!==i.blurSamples&&(u.defines.VSM_SAMPLES=i.blurSamples,p.defines.VSM_SAMPLES=i.blurSamples,u.needsUpdate=!0,p.needsUpdate=!0),null===i.mapPass&&(i.mapPass=new lO(n.x,n.y)),u.uniforms.shadow_pass.value=i.map.texture,u.uniforms.resolution.value=i.mapSize,u.uniforms.radius.value=i.radius,t.setRenderTarget(i.mapPass),t.clear(),t.renderBufferDirect(s,null,r,u,m,null),p.uniforms.shadow_pass.value=i.mapPass.texture,p.uniforms.resolution.value=i.mapSize,p.uniforms.radius.value=i.radius,t.setRenderTarget(i.map),t.clear(),t.renderBufferDirect(s,null,r,p,m,null)}function y(e,i,s,n){let r=null;const a=!0===s.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)r=a;else if(r=!0===s.isPointLight?l:o,t.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0){const t=r.uuid,e=i.uuid;let s=h[t];void 0===s&&(s={},h[t]=s);let n=s[e];void 0===n&&(n=r.clone(),s[e]=n),r=n}if(r.visible=i.visible,r.wireframe=i.wireframe,r.side=3===n?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:d[i.side],r.alphaMap=i.alphaMap,r.alphaTest=i.alphaTest,r.map=i.map,r.clipShadows=i.clipShadows,r.clippingPlanes=i.clippingPlanes,r.clipIntersection=i.clipIntersection,r.displacementMap=i.displacementMap,r.displacementScale=i.displacementScale,r.displacementBias=i.displacementBias,r.wireframeLinewidth=i.wireframeLinewidth,r.linewidth=i.linewidth,!0===s.isPointLight&&!0===r.isMeshDistanceMaterial){t.properties.get(r).light=s}return r}function S(i,n,r,a,o){if(!1===i.visible)return;if(i.layers.test(n.layers)&&(i.isMesh||i.isLine||i.isPoints)&&(i.castShadow||i.receiveShadow&&3===o)&&(!i.frustumCulled||s.intersectsObject(i))){i.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,i.matrixWorld);const s=e.update(i),n=i.material;if(Array.isArray(n)){const e=s.groups;for(let l=0,h=e.length;l<h;l++){const h=e[l],c=n[h.materialIndex];if(c&&c.visible){const e=y(i,c,a,o);t.renderBufferDirect(r,null,s,e,i,h)}}}else if(n.visible){const e=y(i,n,a,o);t.renderBufferDirect(r,null,s,e,i,null)}}const l=i.children;for(let t=0,e=l.length;t<e;t++)S(l[t],n,r,a,o)}this.render=function(e,i,o){if(!1===_.enabled)return;if(!1===_.autoUpdate&&!1===_.needsUpdate)return;if(0===e.length)return;const l=t.getRenderTarget(),h=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),u=t.state;u.setBlending(0),u.buffers.color.setClear(1,1,1,1),u.buffers.depth.setTest(!0),u.setScissorTest(!1);const p=3!==g&&3===this.type,f=3===g&&3!==this.type;for(let l=0,h=e.length;l<h;l++){const h=e[l],d=h.shadow;if(void 0===d)continue;if(!1===d.autoUpdate&&!1===d.needsUpdate)continue;n.copy(d.mapSize);const m=d.getFrameExtents();if(n.multiply(m),r.copy(d.mapSize),(n.x>c||n.y>c)&&(n.x>c&&(r.x=Math.floor(c/m.x),n.x=r.x*m.x,d.mapSize.x=r.x),n.y>c&&(r.y=Math.floor(c/m.y),n.y=r.y*m.y,d.mapSize.y=r.y)),null===d.map||!0===p||!0===f){const t=3!==this.type?{minFilter:UD,magFilter:UD}:{};null!==d.map&&d.map.dispose(),d.map=new lO(n.x,n.y,t),d.map.texture.name=h.name+".shadowMap",d.camera.updateProjectionMatrix()}t.setRenderTarget(d.map),t.clear();const _=d.getViewportCount();for(let t=0;t<_;t++){const e=d.getViewport(t);a.set(r.x*e.x,r.y*e.y,r.x*e.z,r.y*e.w),u.viewport(a),d.updateMatrices(h,t),s=d.getFrustum(),S(i,o,d.camera,h,this.type)}!0!==d.isPointLightShadow&&3===this.type&&v(d,o),d.needsUpdate=!1}g=this.type,_.needsUpdate=!1,t.setRenderTarget(l,h,d)}}function ez(t,e,i){const s=i.isWebGL2;const n=new function(){let e=!1;const i=new aO;let s=null;const n=new aO(0,0,0,0);return{setMask:function(i){s===i||e||(t.colorMask(i,i,i,i),s=i)},setLocked:function(t){e=t},setClear:function(e,s,r,a,o){!0===o&&(e*=a,s*=a,r*=a),i.set(e,s,r,a),!1===n.equals(i)&&(t.clearColor(e,s,r,a),n.copy(i))},reset:function(){e=!1,s=null,n.set(-1,0,0,0)}}},r=new function(){let e=!1,i=null,s=null,n=null;return{setTest:function(e){e?k(t.DEPTH_TEST):V(t.DEPTH_TEST)},setMask:function(s){i===s||e||(t.depthMask(s),i=s)},setFunc:function(e){if(s!==e){switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}s=e}},setLocked:function(t){e=t},setClear:function(e){n!==e&&(t.clearDepth(e),n=e)},reset:function(){e=!1,i=null,s=null,n=null}}},a=new function(){let e=!1,i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null;return{setTest:function(i){e||(i?k(t.STENCIL_TEST):V(t.STENCIL_TEST))},setMask:function(s){i===s||e||(t.stencilMask(s),i=s)},setFunc:function(e,i,a){s===e&&n===i&&r===a||(t.stencilFunc(e,i,a),s=e,n=i,r=a)},setOp:function(e,i,s){a===e&&o===i&&l===s||(t.stencilOp(e,i,s),a=e,o=i,l=s)},setLocked:function(t){e=t},setClear:function(e){h!==e&&(t.clearStencil(e),h=e)},reset:function(){e=!1,i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null}}},o=new WeakMap,l=new WeakMap;let h={},c={},d=new WeakMap,u=[],p=null,f=!1,m=null,_=null,g=null,v=null,y=null,S=null,x=null,T=!1,E=null,b=null,w=null,A=null,C=null;const M=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let P=!1,R=0;const L=t.getParameter(t.VERSION);-1!==L.indexOf("WebGL")?(R=parseFloat(/^WebGL (\d)/.exec(L)[1]),P=R>=1):-1!==L.indexOf("OpenGL ES")&&(R=parseFloat(/^OpenGL ES (\d)/.exec(L)[1]),P=R>=2);let D=null,I={};const O=t.getParameter(t.SCISSOR_BOX),N=t.getParameter(t.VIEWPORT),F=(new aO).fromArray(O),U=(new aO).fromArray(N);function B(e,i,n,r){const a=new Uint8Array(4),o=t.createTexture();t.bindTexture(e,o),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let o=0;o<n;o++)!s||e!==t.TEXTURE_3D&&e!==t.TEXTURE_2D_ARRAY?t.texImage2D(i+o,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,a):t.texImage3D(i,0,t.RGBA,1,1,r,0,t.RGBA,t.UNSIGNED_BYTE,a);return o}const z={};function k(e){!0!==h[e]&&(t.enable(e),h[e]=!0)}function V(e){!1!==h[e]&&(t.disable(e),h[e]=!1)}z[t.TEXTURE_2D]=B(t.TEXTURE_2D,t.TEXTURE_2D,1),z[t.TEXTURE_CUBE_MAP]=B(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),s&&(z[t.TEXTURE_2D_ARRAY]=B(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),z[t.TEXTURE_3D]=B(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),n.setClear(0,0,0,1),r.setClear(1),a.setClear(0),k(t.DEPTH_TEST),r.setFunc(3),X(!1),Y(1),k(t.CULL_FACE),W(0);const H={[gD]:t.FUNC_ADD,[vD]:t.FUNC_SUBTRACT,[yD]:t.FUNC_REVERSE_SUBTRACT};if(s)H[103]=t.MIN,H[104]=t.MAX;else{const t=e.get("EXT_blend_minmax");null!==t&&(H[103]=t.MIN_EXT,H[104]=t.MAX_EXT)}const G={[SD]:t.ZERO,[xD]:t.ONE,[TD]:t.SRC_COLOR,[bD]:t.SRC_ALPHA,[RD]:t.SRC_ALPHA_SATURATE,[MD]:t.DST_COLOR,[AD]:t.DST_ALPHA,[ED]:t.ONE_MINUS_SRC_COLOR,[wD]:t.ONE_MINUS_SRC_ALPHA,[PD]:t.ONE_MINUS_DST_COLOR,[CD]:t.ONE_MINUS_DST_ALPHA};function W(e,i,s,n,r,a,o,l){if(0!==e){if(!1===f&&(k(t.BLEND),f=!0),5===e)r=r||i,a=a||s,o=o||n,i===_&&r===y||(t.blendEquationSeparate(H[i],H[r]),_=i,y=r),s===g&&n===v&&a===S&&o===x||(t.blendFuncSeparate(G[s],G[n],G[a],G[o]),g=s,v=n,S=a,x=o),m=e,T=!1;else if(e!==m||l!==T){if(_===gD&&y===gD||(t.blendEquation(t.FUNC_ADD),_=gD,y=gD),l)switch(e){case 1:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.ONE,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA)}else switch(e){case 1:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case 2:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case 3:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case 4:t.blendFunc(t.ZERO,t.SRC_COLOR)}g=null,v=null,S=null,x=null,m=e,T=l}}else!0===f&&(V(t.BLEND),f=!1)}function X(e){E!==e&&(e?t.frontFace(t.CW):t.frontFace(t.CCW),E=e)}function Y(e){0!==e?(k(t.CULL_FACE),e!==b&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):V(t.CULL_FACE),b=e}function q(e,i,s){e?(k(t.POLYGON_OFFSET_FILL),A===i&&C===s||(t.polygonOffset(i,s),A=i,C=s)):V(t.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:r,stencil:a},enable:k,disable:V,bindFramebuffer:function(e,i){return c[e]!==i&&(t.bindFramebuffer(e,i),c[e]=i,s&&(e===t.DRAW_FRAMEBUFFER&&(c[t.FRAMEBUFFER]=i),e===t.FRAMEBUFFER&&(c[t.DRAW_FRAMEBUFFER]=i)),!0)},drawBuffers:function(s,n){let r=u,a=!1;if(s)if(r=d.get(n),void 0===r&&(r=[],d.set(n,r)),s.isWebGLMultipleRenderTargets){const e=s.texture;if(r.length!==e.length||r[0]!==t.COLOR_ATTACHMENT0){for(let i=0,s=e.length;i<s;i++)r[i]=t.COLOR_ATTACHMENT0+i;r.length=e.length,a=!0}}else r[0]!==t.COLOR_ATTACHMENT0&&(r[0]=t.COLOR_ATTACHMENT0,a=!0);else r[0]!==t.BACK&&(r[0]=t.BACK,a=!0);a&&(i.isWebGL2?t.drawBuffers(r):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(r))},useProgram:function(e){return p!==e&&(t.useProgram(e),p=e,!0)},setBlending:W,setMaterial:function(e,i){2===e.side?V(t.CULL_FACE):k(t.CULL_FACE);let s=1===e.side;i&&(s=!s),X(s),1===e.blending&&!1===e.transparent?W(0):W(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),r.setFunc(e.depthFunc),r.setTest(e.depthTest),r.setMask(e.depthWrite),n.setMask(e.colorWrite);const o=e.stencilWrite;a.setTest(o),o&&(a.setMask(e.stencilWriteMask),a.setFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),a.setOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),q(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage?k(t.SAMPLE_ALPHA_TO_COVERAGE):V(t.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:X,setCullFace:Y,setLineWidth:function(e){e!==w&&(P&&t.lineWidth(e),w=e)},setPolygonOffset:q,setScissorTest:function(e){e?k(t.SCISSOR_TEST):V(t.SCISSOR_TEST)},activeTexture:function(e){void 0===e&&(e=t.TEXTURE0+M-1),D!==e&&(t.activeTexture(e),D=e)},bindTexture:function(e,i,s){void 0===s&&(s=null===D?t.TEXTURE0+M-1:D);let n=I[s];void 0===n&&(n={type:void 0,texture:void 0},I[s]=n),n.type===e&&n.texture===i||(D!==s&&(t.activeTexture(s),D=s),t.bindTexture(e,i||z[e]),n.type=e,n.texture=i)},unbindTexture:function(){const e=I[D];void 0!==e&&void 0!==e.type&&(t.bindTexture(e.type,null),e.type=void 0,e.texture=void 0)},compressedTexImage2D:function(){try{t.compressedTexImage2D.apply(t,arguments)}catch(t){}},compressedTexImage3D:function(){try{t.compressedTexImage3D.apply(t,arguments)}catch(t){}},texImage2D:function(){try{t.texImage2D.apply(t,arguments)}catch(t){}},texImage3D:function(){try{t.texImage3D.apply(t,arguments)}catch(t){}},updateUBOMapping:function(e,i){let s=l.get(i);void 0===s&&(s=new WeakMap,l.set(i,s));let n=s.get(e);void 0===n&&(n=t.getUniformBlockIndex(i,e.name),s.set(e,n))},uniformBlockBinding:function(e,i){const s=l.get(i).get(e);o.get(i)!==s&&(t.uniformBlockBinding(i,s,e.__bindingPointIndex),o.set(i,s))},texStorage2D:function(){try{t.texStorage2D.apply(t,arguments)}catch(t){}},texStorage3D:function(){try{t.texStorage3D.apply(t,arguments)}catch(t){}},texSubImage2D:function(){try{t.texSubImage2D.apply(t,arguments)}catch(t){}},texSubImage3D:function(){try{t.texSubImage3D.apply(t,arguments)}catch(t){}},compressedTexSubImage2D:function(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(t){}},compressedTexSubImage3D:function(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(t){}},scissor:function(e){!1===F.equals(e)&&(t.scissor(e.x,e.y,e.z,e.w),F.copy(e))},viewport:function(e){!1===U.equals(e)&&(t.viewport(e.x,e.y,e.z,e.w),U.copy(e))},reset:function(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),!0===s&&(t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),h={},D=null,I={},c={},d=new WeakMap,u=[],p=null,f=!1,m=null,_=null,g=null,v=null,y=null,S=null,x=null,T=!1,E=null,b=null,w=null,A=null,C=null,F.set(0,0,t.canvas.width,t.canvas.height),U.set(0,0,t.canvas.width,t.canvas.height),n.reset(),r.reset(),a.reset()}}}function iz(t,e,i,s,n,r,a){const o=n.isWebGL2,l=(n.maxTextures,n.maxCubemapSize),h=n.maxTextureSize,c=n.maxSamples,d=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,u="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),p=new WeakMap;let f;const m=new WeakMap;let _=!1;try{_="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function g(t,e){return _?new OffscreenCanvas(t,e):HI("canvas")}function v(t,e,i,s){let n=1;if((t.width>s||t.height>s)&&(n=s/Math.max(t.width,t.height)),n<1||!0===e){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const s=e?NI:Math.floor,r=s(n*t.width),a=s(n*t.height);void 0===f&&(f=g(r,a));const o=i?g(r,a):f;o.width=r,o.height=a;return o.getContext("2d").drawImage(t,0,0,r,a),o}return t}return t}function y(t){return OI(t.width)&&OI(t.height)}function S(t,e){return t.generateMipmaps&&e&&t.minFilter!==UD&&t.minFilter!==kD}function x(e){t.generateMipmap(e)}function T(i,s,n,r,a=!1){if(!1===o)return s;if(null!==i&&void 0!==t[i])return t[i];let l=s;if(s===t.RED&&(n===t.FLOAT&&(l=t.R32F),n===t.HALF_FLOAT&&(l=t.R16F),n===t.UNSIGNED_BYTE&&(l=t.R8)),s===t.RED_INTEGER&&(n===t.UNSIGNED_BYTE&&(l=t.R8UI),n===t.UNSIGNED_SHORT&&(l=t.R16UI),n===t.UNSIGNED_INT&&(l=t.R32UI),n===t.BYTE&&(l=t.R8I),n===t.SHORT&&(l=t.R16I),n===t.INT&&(l=t.R32I)),s===t.RG&&(n===t.FLOAT&&(l=t.RG32F),n===t.HALF_FLOAT&&(l=t.RG16F),n===t.UNSIGNED_BYTE&&(l=t.RG8)),s===t.RGBA){const e=a?cI:KI.getTransfer(r);n===t.FLOAT&&(l=t.RGBA32F),n===t.HALF_FLOAT&&(l=t.RGBA16F),n===t.UNSIGNED_BYTE&&(l=e===dI?t.SRGB8_ALPHA8:t.RGBA8),n===t.UNSIGNED_SHORT_4_4_4_4&&(l=t.RGBA4),n===t.UNSIGNED_SHORT_5_5_5_1&&(l=t.RGB5_A1)}return l!==t.R16F&&l!==t.R32F&&l!==t.RG16F&&l!==t.RG32F&&l!==t.RGBA16F&&l!==t.RGBA32F||e.get("EXT_color_buffer_float"),l}function E(t,e,i){return!0===S(t,i)||t.isFramebufferTexture&&t.minFilter!==UD&&t.minFilter!==kD?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function b(e){return e===UD||1004===e||e===zD?t.NEAREST:t.LINEAR}function w(t){const e=t.target;e.removeEventListener("dispose",w),function(t){const e=s.get(t);if(void 0===e.__webglInit)return;const i=t.source,n=m.get(i);if(n){const s=n[e.__cacheKey];s.usedTimes--,0===s.usedTimes&&C(t),0===Object.keys(n).length&&m.delete(i)}s.remove(t)}(e),e.isVideoTexture&&p.delete(e)}function A(e){const i=e.target;i.removeEventListener("dispose",A),function(e){const i=e.texture,n=s.get(e),r=s.get(i);void 0!==r.__webglTexture&&(t.deleteTexture(r.__webglTexture),a.memory.textures--);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i<n.__webglFramebuffer[e].length;i++)t.deleteFramebuffer(n.__webglFramebuffer[e][i]);else t.deleteFramebuffer(n.__webglFramebuffer[e]);n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer[e])}else{if(Array.isArray(n.__webglFramebuffer))for(let e=0;e<n.__webglFramebuffer.length;e++)t.deleteFramebuffer(n.__webglFramebuffer[e]);else t.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&t.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&t.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let e=0;e<n.__webglColorRenderbuffer.length;e++)n.__webglColorRenderbuffer[e]&&t.deleteRenderbuffer(n.__webglColorRenderbuffer[e]);n.__webglDepthRenderbuffer&&t.deleteRenderbuffer(n.__webglDepthRenderbuffer)}if(e.isWebGLMultipleRenderTargets)for(let e=0,n=i.length;e<n;e++){const n=s.get(i[e]);n.__webglTexture&&(t.deleteTexture(n.__webglTexture),a.memory.textures--),s.remove(i[e])}s.remove(i),s.remove(e)}(i)}function C(e){const i=s.get(e);t.deleteTexture(i.__webglTexture);const n=e.source;delete m.get(n)[i.__cacheKey],a.memory.textures--}let M=0;function P(e,n){const r=s.get(e);if(e.isVideoTexture&&function(t){const e=a.render.frame;p.get(t)!==e&&(p.set(t,e),t.update())}(e),!1===e.isRenderTargetTexture&&e.version>0&&r.__version!==e.version){const t=e.image;if(null===t);else if(!1!==t.complete)return void N(r,e,n)}i.bindTexture(t.TEXTURE_2D,r.__webglTexture,t.TEXTURE0+n)}const R={[OD]:t.REPEAT,[ND]:t.CLAMP_TO_EDGE,[FD]:t.MIRRORED_REPEAT},L={[UD]:t.NEAREST,[BD]:t.NEAREST_MIPMAP_NEAREST,[zD]:t.NEAREST_MIPMAP_LINEAR,[kD]:t.LINEAR,[VD]:t.LINEAR_MIPMAP_NEAREST,[HD]:t.LINEAR_MIPMAP_LINEAR},D={[mI]:t.NEVER,[TI]:t.ALWAYS,[_I]:t.LESS,[vI]:t.LEQUAL,[gI]:t.EQUAL,[xI]:t.GEQUAL,[yI]:t.GREATER,[SI]:t.NOTEQUAL};function I(i,r,a){if(a?(t.texParameteri(i,t.TEXTURE_WRAP_S,R[r.wrapS]),t.texParameteri(i,t.TEXTURE_WRAP_T,R[r.wrapT]),i!==t.TEXTURE_3D&&i!==t.TEXTURE_2D_ARRAY||t.texParameteri(i,t.TEXTURE_WRAP_R,R[r.wrapR]),t.texParameteri(i,t.TEXTURE_MAG_FILTER,L[r.magFilter]),t.texParameteri(i,t.TEXTURE_MIN_FILTER,L[r.minFilter])):(t.texParameteri(i,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(i,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i!==t.TEXTURE_3D&&i!==t.TEXTURE_2D_ARRAY||t.texParameteri(i,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),r.wrapS!==ND||r.wrapT,t.texParameteri(i,t.TEXTURE_MAG_FILTER,b(r.magFilter)),t.texParameteri(i,t.TEXTURE_MIN_FILTER,b(r.minFilter)),r.minFilter!==UD&&r.minFilter),r.compareFunction&&(t.texParameteri(i,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(i,t.TEXTURE_COMPARE_FUNC,D[r.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){const a=e.get("EXT_texture_filter_anisotropic");if(r.magFilter===UD)return;if(r.minFilter!==zD&&r.minFilter!==HD)return;if(r.type===qD&&!1===e.has("OES_texture_float_linear"))return;if(!1===o&&r.type===jD&&!1===e.has("OES_texture_half_float_linear"))return;(r.anisotropy>1||s.get(r).__currentAnisotropy)&&(t.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r.anisotropy,n.getMaxAnisotropy())),s.get(r).__currentAnisotropy=r.anisotropy)}}function O(e,i){let s=!1;void 0===e.__webglInit&&(e.__webglInit=!0,i.addEventListener("dispose",w));const n=i.source;let r=m.get(n);void 0===r&&(r={},m.set(n,r));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(i);if(o!==e.__cacheKey){void 0===r[o]&&(r[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,s=!0),r[o].usedTimes++;const n=r[e.__cacheKey];void 0!==n&&(r[e.__cacheKey].usedTimes--,0===n.usedTimes&&C(i)),e.__cacheKey=o,e.__webglTexture=r[o].texture}return s}function N(e,n,a){let l=t.TEXTURE_2D;(n.isDataArrayTexture||n.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),n.isData3DTexture&&(l=t.TEXTURE_3D);const c=O(e,n),d=n.source;i.bindTexture(l,e.__webglTexture,t.TEXTURE0+a);const u=s.get(d);if(d.version!==u.__version||!0===c){i.activeTexture(t.TEXTURE0+a);const e=KI.getPrimaries(KI.workingColorSpace),s=n.colorSpace===rI?null:KI.getPrimaries(n.colorSpace),p=n.colorSpace===rI||e===s?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,n.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,n.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,p);const f=function(t){return!o&&(t.wrapS!==ND||t.wrapT!==ND||t.minFilter!==UD&&t.minFilter!==kD)}(n)&&!1===y(n.image);let m=v(n.image,f,!1,h);m=V(n,m);const _=y(m)||o,g=r.convert(n.format,n.colorSpace);let b,w=r.convert(n.type),A=T(n.internalFormat,g,w,n.colorSpace,n.isVideoTexture);I(l,n,_);const C=n.mipmaps,M=o&&!0!==n.isVideoTexture,P=void 0===u.__version||!0===c,R=E(n,m,_);if(n.isDepthTexture)A=t.DEPTH_COMPONENT,o?A=n.type===qD?t.DEPTH_COMPONENT32F:n.type===YD?t.DEPTH_COMPONENT24:n.type===$D?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT16:n.type,n.format===ZD&&A===t.DEPTH_COMPONENT&&n.type!==WD&&n.type!==YD&&(n.type=YD,w=r.convert(n.type)),n.format===QD&&A===t.DEPTH_COMPONENT&&(A=t.DEPTH_STENCIL,n.type!==$D&&(n.type=$D,w=r.convert(n.type))),P&&(M?i.texStorage2D(t.TEXTURE_2D,1,A,m.width,m.height):i.texImage2D(t.TEXTURE_2D,0,A,m.width,m.height,0,g,w,null));else if(n.isDataTexture)if(C.length>0&&_){M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,w,b.data):i.texImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,g,w,b.data);n.generateMipmaps=!1}else M?(P&&i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height),i.texSubImage2D(t.TEXTURE_2D,0,0,0,m.width,m.height,g,w,m.data)):i.texImage2D(t.TEXTURE_2D,0,A,m.width,m.height,0,g,w,m.data);else if(n.isCompressedTexture)if(n.isCompressedArrayTexture){M&&P&&i.texStorage3D(t.TEXTURE_2D_ARRAY,R,A,C[0].width,C[0].height,m.depth);for(let e=0,s=C.length;e<s;e++)b=C[e],n.format!==KD?null!==g&&(M?i.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,b.width,b.height,m.depth,g,b.data,0,0):i.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,A,b.width,b.height,m.depth,0,b.data,0,0)):M?i.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,b.width,b.height,m.depth,g,w,b.data):i.texImage3D(t.TEXTURE_2D_ARRAY,e,A,b.width,b.height,m.depth,0,g,w,b.data)}else{M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],n.format!==KD?null!==g&&(M?i.compressedTexSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,b.data):i.compressedTexImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,b.data)):M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,b.width,b.height,g,w,b.data):i.texImage2D(t.TEXTURE_2D,e,A,b.width,b.height,0,g,w,b.data)}else if(n.isDataArrayTexture)M?(P&&i.texStorage3D(t.TEXTURE_2D_ARRAY,R,A,m.width,m.height,m.depth),i.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,m.width,m.height,m.depth,g,w,m.data)):i.texImage3D(t.TEXTURE_2D_ARRAY,0,A,m.width,m.height,m.depth,0,g,w,m.data);else if(n.isData3DTexture)M?(P&&i.texStorage3D(t.TEXTURE_3D,R,A,m.width,m.height,m.depth),i.texSubImage3D(t.TEXTURE_3D,0,0,0,0,m.width,m.height,m.depth,g,w,m.data)):i.texImage3D(t.TEXTURE_3D,0,A,m.width,m.height,m.depth,0,g,w,m.data);else if(n.isFramebufferTexture){if(P)if(M)i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height);else{let e=m.width,s=m.height;for(let n=0;n<R;n++)i.texImage2D(t.TEXTURE_2D,n,A,e,s,0,g,w,null),e>>=1,s>>=1}}else if(C.length>0&&_){M&&P&&i.texStorage2D(t.TEXTURE_2D,R,A,C[0].width,C[0].height);for(let e=0,s=C.length;e<s;e++)b=C[e],M?i.texSubImage2D(t.TEXTURE_2D,e,0,0,g,w,b):i.texImage2D(t.TEXTURE_2D,e,A,g,w,b);n.generateMipmaps=!1}else M?(P&&i.texStorage2D(t.TEXTURE_2D,R,A,m.width,m.height),i.texSubImage2D(t.TEXTURE_2D,0,0,0,g,w,m)):i.texImage2D(t.TEXTURE_2D,0,A,g,w,m);S(n,_)&&x(l),u.__version=d.version,n.onUpdate&&n.onUpdate(n)}e.__version=n.version}function F(e,n,a,o,l,h){const c=r.convert(a.format,a.colorSpace),u=r.convert(a.type),p=T(a.internalFormat,c,u,a.colorSpace);if(!s.get(n).__hasExternalTextures){const e=Math.max(1,n.width>>h),s=Math.max(1,n.height>>h);l===t.TEXTURE_3D||l===t.TEXTURE_2D_ARRAY?i.texImage3D(l,h,p,e,s,n.depth,0,c,u,null):i.texImage2D(l,h,p,e,s,0,c,u,null)}i.bindFramebuffer(t.FRAMEBUFFER,e),k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,l,s.get(a).__webglTexture,0,z(n)):(l===t.TEXTURE_2D||l>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,o,l,s.get(a).__webglTexture,h),i.bindFramebuffer(t.FRAMEBUFFER,null)}function U(e,i,s){if(t.bindRenderbuffer(t.RENDERBUFFER,e),i.depthBuffer&&!i.stencilBuffer){let n=!0===o?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(s||k(i)){const e=i.depthTexture;e&&e.isDepthTexture&&(e.type===qD?n=t.DEPTH_COMPONENT32F:e.type===YD&&(n=t.DEPTH_COMPONENT24));const s=z(i);k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,s,n,i.width,i.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,s,n,i.width,i.height)}else t.renderbufferStorage(t.RENDERBUFFER,n,i.width,i.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e)}else if(i.depthBuffer&&i.stencilBuffer){const n=z(i);s&&!1===k(i)?t.renderbufferStorageMultisample(t.RENDERBUFFER,n,t.DEPTH24_STENCIL8,i.width,i.height):k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,n,t.DEPTH24_STENCIL8,i.width,i.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,i.width,i.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e)}else{const e=!0===i.isWebGLMultipleRenderTargets?i.texture:[i.texture];for(let n=0;n<e.length;n++){const a=e[n],o=r.convert(a.format,a.colorSpace),l=r.convert(a.type),h=T(a.internalFormat,o,l,a.colorSpace),c=z(i);s&&!1===k(i)?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,h,i.width,i.height):k(i)?d.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,h,i.width,i.height):t.renderbufferStorage(t.RENDERBUFFER,h,i.width,i.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function B(e){const n=s.get(e),r=!0===e.isWebGLCubeRenderTarget;if(e.depthTexture&&!n.__autoAllocateDepthBuffer){if(r)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,n){if(n&&n.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(i.bindFramebuffer(t.FRAMEBUFFER,e),!n.depthTexture||!n.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");s.get(n.depthTexture).__webglTexture&&n.depthTexture.image.width===n.width&&n.depthTexture.image.height===n.height||(n.depthTexture.image.width=n.width,n.depthTexture.image.height=n.height,n.depthTexture.needsUpdate=!0),P(n.depthTexture,0);const r=s.get(n.depthTexture).__webglTexture,a=z(n);if(n.depthTexture.format===ZD)k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,r,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,r,0);else{if(n.depthTexture.format!==QD)throw new Error("Unknown depthTexture format");k(n)?d.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,r,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,r,0)}}(n.__webglFramebuffer,e)}else if(r){n.__webglDepthbuffer=[];for(let s=0;s<6;s++)i.bindFramebuffer(t.FRAMEBUFFER,n.__webglFramebuffer[s]),n.__webglDepthbuffer[s]=t.createRenderbuffer(),U(n.__webglDepthbuffer[s],e,!1)}else i.bindFramebuffer(t.FRAMEBUFFER,n.__webglFramebuffer),n.__webglDepthbuffer=t.createRenderbuffer(),U(n.__webglDepthbuffer,e,!1);i.bindFramebuffer(t.FRAMEBUFFER,null)}function z(t){return Math.min(c,t.samples)}function k(t){const i=s.get(t);return o&&t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function V(t,i){const s=t.colorSpace,n=t.format;t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||t.format===bI||s!==oI&&s!==rI&&KI.getTransfer(s)===dI&&!1===o&&(!0===e.has("EXT_sRGB")&&n===KD?(t.format=bI,t.minFilter=kD,t.generateMipmaps=!1):i=tO.sRGBToLinear(i)),i}this.allocateTextureUnit=function(){const t=M;return M+=1,t},this.resetTextureUnits=function(){M=0},this.setTexture2D=P,this.setTexture2DArray=function(e,n){const r=s.get(e);e.version>0&&r.__version!==e.version?N(r,e,n):i.bindTexture(t.TEXTURE_2D_ARRAY,r.__webglTexture,t.TEXTURE0+n)},this.setTexture3D=function(e,n){const r=s.get(e);e.version>0&&r.__version!==e.version?N(r,e,n):i.bindTexture(t.TEXTURE_3D,r.__webglTexture,t.TEXTURE0+n)},this.setTextureCube=function(e,n){const a=s.get(e);e.version>0&&a.__version!==e.version?function(e,n,a){if(6!==n.image.length)return;const h=O(e,n),c=n.source;i.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+a);const d=s.get(c);if(c.version!==d.__version||!0===h){i.activeTexture(t.TEXTURE0+a);const e=KI.getPrimaries(KI.workingColorSpace),s=n.colorSpace===rI?null:KI.getPrimaries(n.colorSpace),u=n.colorSpace===rI||e===s?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,n.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,n.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const p=n.isCompressedTexture||n.image[0].isCompressedTexture,f=n.image[0]&&n.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=p||f?f?n.image[t].image:n.image[t]:v(n.image[t],!1,!0,l),m[t]=V(n,m[t]);const _=m[0],g=y(_)||o,b=r.convert(n.format,n.colorSpace),w=r.convert(n.type),A=T(n.internalFormat,b,w,n.colorSpace),C=o&&!0!==n.isVideoTexture,M=void 0===d.__version||!0===h;let P,R=E(n,_,g);if(I(t.TEXTURE_CUBE_MAP,n,g),p){C&&M&&i.texStorage2D(t.TEXTURE_CUBE_MAP,R,A,_.width,_.height);for(let e=0;e<6;e++){P=m[e].mipmaps;for(let s=0;s<P.length;s++){const r=P[s];n.format!==KD?null!==b&&(C?i.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,0,0,r.width,r.height,b,r.data):i.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,A,r.width,r.height,0,r.data)):C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,0,0,r.width,r.height,b,w,r.data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s,A,r.width,r.height,0,b,w,r.data)}}}else{P=n.mipmaps,C&&M&&(P.length>0&&R++,i.texStorage2D(t.TEXTURE_CUBE_MAP,R,A,m[0].width,m[0].height));for(let e=0;e<6;e++)if(f){C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,b,w,m[e].data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,A,m[e].width,m[e].height,0,b,w,m[e].data);for(let s=0;s<P.length;s++){const n=P[s].image[e].image;C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,0,0,n.width,n.height,b,w,n.data):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,A,n.width,n.height,0,b,w,n.data)}}else{C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,b,w,m[e]):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,A,b,w,m[e]);for(let s=0;s<P.length;s++){const n=P[s];C?i.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,0,0,b,w,n.image[e]):i.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s+1,A,b,w,n.image[e])}}}S(n,g)&&x(t.TEXTURE_CUBE_MAP),d.__version=c.version,n.onUpdate&&n.onUpdate(n)}e.__version=n.version}(a,e,n):i.bindTexture(t.TEXTURE_CUBE_MAP,a.__webglTexture,t.TEXTURE0+n)},this.rebindTextures=function(e,i,n){const r=s.get(e);void 0!==i&&F(r.__webglFramebuffer,e,e.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),void 0!==n&&B(e)},this.setupRenderTarget=function(e){const l=e.texture,h=s.get(e),c=s.get(l);e.addEventListener("dispose",A),!0!==e.isWebGLMultipleRenderTargets&&(void 0===c.__webglTexture&&(c.__webglTexture=t.createTexture()),c.__version=l.version,a.memory.textures++);const d=!0===e.isWebGLCubeRenderTarget,u=!0===e.isWebGLMultipleRenderTargets,p=y(e)||o;if(d){h.__webglFramebuffer=[];for(let e=0;e<6;e++)if(o&&l.mipmaps&&l.mipmaps.length>0){h.__webglFramebuffer[e]=[];for(let i=0;i<l.mipmaps.length;i++)h.__webglFramebuffer[e][i]=t.createFramebuffer()}else h.__webglFramebuffer[e]=t.createFramebuffer()}else{if(o&&l.mipmaps&&l.mipmaps.length>0){h.__webglFramebuffer=[];for(let e=0;e<l.mipmaps.length;e++)h.__webglFramebuffer[e]=t.createFramebuffer()}else h.__webglFramebuffer=t.createFramebuffer();if(u&&n.drawBuffers){const i=e.texture;for(let e=0,n=i.length;e<n;e++){const n=s.get(i[e]);void 0===n.__webglTexture&&(n.__webglTexture=t.createTexture(),a.memory.textures++)}}if(o&&e.samples>0&&!1===k(e)){const s=u?l:[l];h.__webglMultisampledFramebuffer=t.createFramebuffer(),h.__webglColorRenderbuffer=[],i.bindFramebuffer(t.FRAMEBUFFER,h.__webglMultisampledFramebuffer);for(let i=0;i<s.length;i++){const n=s[i];h.__webglColorRenderbuffer[i]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,h.__webglColorRenderbuffer[i]);const a=r.convert(n.format,n.colorSpace),o=r.convert(n.type),l=T(n.internalFormat,a,o,n.colorSpace,!0===e.isXRRenderTarget),c=z(e);t.renderbufferStorageMultisample(t.RENDERBUFFER,c,l,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+i,t.RENDERBUFFER,h.__webglColorRenderbuffer[i])}t.bindRenderbuffer(t.RENDERBUFFER,null),e.depthBuffer&&(h.__webglDepthRenderbuffer=t.createRenderbuffer(),U(h.__webglDepthRenderbuffer,e,!0)),i.bindFramebuffer(t.FRAMEBUFFER,null)}}if(d){i.bindTexture(t.TEXTURE_CUBE_MAP,c.__webglTexture),I(t.TEXTURE_CUBE_MAP,l,p);for(let i=0;i<6;i++)if(o&&l.mipmaps&&l.mipmaps.length>0)for(let s=0;s<l.mipmaps.length;s++)F(h.__webglFramebuffer[i][s],e,l,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+i,s);else F(h.__webglFramebuffer[i],e,l,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+i,0);S(l,p)&&x(t.TEXTURE_CUBE_MAP),i.unbindTexture()}else if(u){const n=e.texture;for(let r=0,a=n.length;r<a;r++){const a=n[r],o=s.get(a);i.bindTexture(t.TEXTURE_2D,o.__webglTexture),I(t.TEXTURE_2D,a,p),F(h.__webglFramebuffer,e,a,t.COLOR_ATTACHMENT0+r,t.TEXTURE_2D,0),S(a,p)&&x(t.TEXTURE_2D)}i.unbindTexture()}else{let s=t.TEXTURE_2D;if((e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&o&&(s=e.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),i.bindTexture(s,c.__webglTexture),I(s,l,p),o&&l.mipmaps&&l.mipmaps.length>0)for(let i=0;i<l.mipmaps.length;i++)F(h.__webglFramebuffer[i],e,l,t.COLOR_ATTACHMENT0,s,i);else F(h.__webglFramebuffer,e,l,t.COLOR_ATTACHMENT0,s,0);S(l,p)&&x(s),i.unbindTexture()}e.depthBuffer&&B(e)},this.updateRenderTargetMipmap=function(e){const n=y(e)||o,r=!0===e.isWebGLMultipleRenderTargets?e.texture:[e.texture];for(let a=0,o=r.length;a<o;a++){const o=r[a];if(S(o,n)){const n=e.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,r=s.get(o).__webglTexture;i.bindTexture(n,r),x(n),i.unbindTexture()}}},this.updateMultisampleRenderTarget=function(e){if(o&&e.samples>0&&!1===k(e)){const n=e.isWebGLMultipleRenderTargets?e.texture:[e.texture],r=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const l=[],h=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=s.get(e),d=!0===e.isWebGLMultipleRenderTargets;if(d)for(let e=0;e<n.length;e++)i.bindFramebuffer(t.FRAMEBUFFER,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),i.bindFramebuffer(t.FRAMEBUFFER,c.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);i.bindFramebuffer(t.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let i=0;i<n.length;i++){l.push(t.COLOR_ATTACHMENT0+i),e.depthBuffer&&l.push(h);const p=void 0!==c.__ignoreDepthValues&&c.__ignoreDepthValues;if(!1===p&&(e.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),e.stencilBuffer&&(o|=t.STENCIL_BUFFER_BIT)),d&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c.__webglColorRenderbuffer[i]),!0===p&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[h]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[h])),d){const e=s.get(n[i]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}t.blitFramebuffer(0,0,r,a,0,0,r,a,o,t.NEAREST),u&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,l)}if(i.bindFramebuffer(t.READ_FRAMEBUFFER,null),i.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),d)for(let e=0;e<n.length;e++){i.bindFramebuffer(t.FRAMEBUFFER,c.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,c.__webglColorRenderbuffer[e]);const r=s.get(n[e]).__webglTexture;i.bindFramebuffer(t.FRAMEBUFFER,c.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,r,0)}i.bindFramebuffer(t.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}},this.setupDepthRenderbuffer=B,this.setupFrameBufferTexture=F,this.useMultisampledRTT=k}function sz(t,e,i){const s=i.isWebGL2;return{convert:function(i,n=""){let r;const a=KI.getTransfer(n);if(i===GD)return t.UNSIGNED_BYTE;if(1017===i)return t.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return t.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return t.BYTE;if(1011===i)return t.SHORT;if(i===WD)return t.UNSIGNED_SHORT;if(i===XD)return t.INT;if(i===YD)return t.UNSIGNED_INT;if(i===qD)return t.FLOAT;if(i===jD)return s?t.HALF_FLOAT:(r=e.get("OES_texture_half_float"),null!==r?r.HALF_FLOAT_OES:null);if(1021===i)return t.ALPHA;if(i===KD)return t.RGBA;if(1024===i)return t.LUMINANCE;if(1025===i)return t.LUMINANCE_ALPHA;if(i===ZD)return t.DEPTH_COMPONENT;if(i===QD)return t.DEPTH_STENCIL;if(i===bI)return r=e.get("EXT_sRGB"),null!==r?r.SRGB_ALPHA_EXT:null;if(1028===i)return t.RED;if(1029===i)return t.RED_INTEGER;if(1030===i)return t.RG;if(1031===i)return t.RG_INTEGER;if(1033===i)return t.RGBA_INTEGER;if(i===JD||i===tI||i===eI||i===iI)if(a===dI){if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(i===JD)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===tI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===eI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===iI)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=e.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(i===JD)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===tI)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===eI)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===iI)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){if(r=e.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===i)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i)return r=e.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(37492===i||37496===i){if(r=e.get("WEBGL_compressed_texture_etc"),null===r)return null;if(37492===i)return a===dI?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(37496===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){if(r=e.get("WEBGL_compressed_texture_astc"),null===r)return null;if(37808===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return a===dI?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===sI||36494===i||36495===i){if(r=e.get("EXT_texture_compression_bptc"),null===r)return null;if(i===sI)return a===dI?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(36494===i)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(36495===i)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(36283===i||36284===i||36285===i||36286===i){if(r=e.get("EXT_texture_compression_rgtc"),null===r)return null;if(i===sI)return r.COMPRESSED_RED_RGTC1_EXT;if(36284===i)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(36285===i)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(36286===i)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===$D?s?t.UNSIGNED_INT_24_8:(r=e.get("WEBGL_depth_texture"),null!==r?r.UNSIGNED_INT_24_8_WEBGL:null):void 0!==t[i]?t[i]:null}}}class nz extends xF{constructor(t=[]){super(),this.isArrayCamera=!0,this.cameras=t}}class rz extends pN{constructor(){super(),this.isGroup=!0,this.type="Group"}}const az={type:"move"};class oz{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new rz,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new rz,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new uO,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new uO),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new rz,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new uO,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new uO),this._grip}dispatchEvent(t){return null!==this._targetRay&&this._targetRay.dispatchEvent(t),null!==this._grip&&this._grip.dispatchEvent(t),null!==this._hand&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(t,e,i){let s=null,n=null,r=null;const a=this._targetRay,o=this._grip,l=this._hand;if(t&&"visible-blurred"!==e.session.visibilityState){if(l&&t.hand){r=!0;for(const s of t.hand.values()){const t=e.getJointPose(s,i),n=this._getHandJoint(l,s);null!==t&&(n.matrix.fromArray(t.transform.matrix),n.matrix.decompose(n.position,n.rotation,n.scale),n.matrixWorldNeedsUpdate=!0,n.jointRadius=t.radius),n.visible=null!==t}const s=l.joints["index-finger-tip"],n=l.joints["thumb-tip"],a=s.position.distanceTo(n.position),o=.02,h=.005;l.inputState.pinching&&a>o+h?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-h&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(n=e.getPose(t.gripSpace,i),null!==n&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(s=e.getPose(t.targetRaySpace,i),null===s&&null!==n&&(s=n),null!==s&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(az)))}return null!==a&&(a.visible=null!==s),null!==o&&(o.visible=null!==n),null!==l&&(l.visible=null!==r),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const i=new rz;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}class lz extends rO{constructor(t,e,i,s,n,r,a,o,l,h){if((h=void 0!==h?h:ZD)!==ZD&&h!==QD)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===i&&h===ZD&&(i=YD),void 0===i&&h===QD&&(i=$D),super(null,s,n,r,a,o,h,i,l),this.isDepthTexture=!0,this.image={width:t,height:e},this.magFilter=void 0!==a?a:UD,this.minFilter=void 0!==o?o:UD,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return null!==this.compareFunction&&(e.compareFunction=this.compareFunction),e}}class hz extends CI{constructor(t,e){super();const i=this;let s=null,n=1,r=null,a="local-floor",o=1,l=null,h=null,c=null,d=null,u=null,p=null;const f=e.getContextAttributes();let m=null,_=null;const g=[],v=[],y=new xF;y.layers.enable(1),y.viewport=new aO;const S=new xF;S.layers.enable(2),S.viewport=new aO;const x=[y,S],T=new nz;T.layers.enable(1),T.layers.enable(2);let E=null,b=null;function w(t){const e=v.indexOf(t.inputSource);if(-1===e)return;const i=g[e];void 0!==i&&(i.update(t.inputSource,t.frame,l||r),i.dispatchEvent({type:t.type,data:t.inputSource}))}function A(){s.removeEventListener("select",w),s.removeEventListener("selectstart",w),s.removeEventListener("selectend",w),s.removeEventListener("squeeze",w),s.removeEventListener("squeezestart",w),s.removeEventListener("squeezeend",w),s.removeEventListener("end",A),s.removeEventListener("inputsourceschange",C);for(let t=0;t<g.length;t++){const e=v[t];null!==e&&(v[t]=null,g[t].disconnect(e))}E=null,b=null,t.setRenderTarget(m),u=null,d=null,c=null,s=null,_=null,D.stop(),i.isPresenting=!1,i.dispatchEvent({type:"sessionend"})}function C(t){for(let e=0;e<t.removed.length;e++){const i=t.removed[e],s=v.indexOf(i);s>=0&&(v[s]=null,g[s].disconnect(i))}for(let e=0;e<t.added.length;e++){const i=t.added[e];let s=v.indexOf(i);if(-1===s){for(let t=0;t<g.length;t++){if(t>=v.length){v.push(i),s=t;break}if(null===v[t]){v[t]=i,s=t;break}}if(-1===s)break}const n=g[s];n&&n.connect(i)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getGripSpace()},this.getHand=function(t){let e=g[t];return void 0===e&&(e=new oz,g[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){n=t,i.isPresenting},this.setReferenceSpaceType=function(t){a=t,i.isPresenting},this.getReferenceSpace=function(){return l||r},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==d?d:u},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(h){if(s=h,null!==s){if(m=t.getRenderTarget(),s.addEventListener("select",w),s.addEventListener("selectstart",w),s.addEventListener("selectend",w),s.addEventListener("squeeze",w),s.addEventListener("squeezestart",w),s.addEventListener("squeezeend",w),s.addEventListener("end",A),s.addEventListener("inputsourceschange",C),!0!==f.xrCompatible&&await e.makeXRCompatible(),void 0===s.renderState.layers||!1===t.capabilities.isWebGL2){const i={antialias:void 0!==s.renderState.layers||f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:n};u=new XRWebGLLayer(s,e,i),s.updateRenderState({baseLayer:u}),_=new lO(u.framebufferWidth,u.framebufferHeight,{format:KD,type:GD,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let i=null,r=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,i=f.stencil?QD:ZD,r=f.stencil?$D:YD);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:n};c=new XRWebGLBinding(s,e),d=c.createProjectionLayer(o),s.updateRenderState({layers:[d]}),_=new lO(d.textureWidth,d.textureHeight,{format:KD,type:GD,depthTexture:new lz(d.textureWidth,d.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,i),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0});t.properties.get(_).__ignoreDepthValues=d.ignoreDepthValues}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,r=await s.requestReferenceSpace(a),D.setContext(s),D.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==s)return s.environmentBlendMode};const M=new uO,P=new uO;function R(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===s)return;T.near=S.near=y.near=t.near,T.far=S.far=y.far=t.far,E===T.near&&b===T.far||(s.updateRenderState({depthNear:T.near,depthFar:T.far}),E=T.near,b=T.far);const e=t.parent,i=T.cameras;R(T,e);for(let t=0;t<i.length;t++)R(i[t],e);2===i.length?function(t,e,i){M.setFromMatrixPosition(e.matrixWorld),P.setFromMatrixPosition(i.matrixWorld);const s=M.distanceTo(P),n=e.projectionMatrix.elements,r=i.projectionMatrix.elements,a=n[14]/(n[10]-1),o=n[14]/(n[10]+1),l=(n[9]+1)/n[5],h=(n[9]-1)/n[5],c=(n[8]-1)/n[0],d=(r[8]+1)/r[0],u=a*c,p=a*d,f=s/(-c+d),m=f*-c;e.matrixWorld.decompose(t.position,t.quaternion,t.scale),t.translateX(m),t.translateZ(f),t.matrixWorld.compose(t.position,t.quaternion,t.scale),t.matrixWorldInverse.copy(t.matrixWorld).invert();const _=a+f,g=o+f,v=u-m,y=p+(s-m),S=l*o/g*_,x=h*o/g*_;t.projectionMatrix.makePerspective(v,y,S,x,_,g),t.projectionMatrixInverse.copy(t.projectionMatrix).invert()}(T,y,S):T.projectionMatrix.copy(y.projectionMatrix),function(t,e,i){null===i?t.matrix.copy(e.matrixWorld):(t.matrix.copy(i.matrixWorld),t.matrix.invert(),t.matrix.multiply(e.matrixWorld));t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(!0),t.projectionMatrix.copy(e.projectionMatrix),t.projectionMatrixInverse.copy(e.projectionMatrixInverse),t.isPerspectiveCamera&&(t.fov=2*RI*Math.atan(1/t.projectionMatrix.elements[5]),t.zoom=1)}(t,T,e)},this.getCamera=function(){return T},this.getFoveation=function(){if(null!==d||null!==u)return o},this.setFoveation=function(t){o=t,null!==d&&(d.fixedFoveation=t),null!==u&&void 0!==u.fixedFoveation&&(u.fixedFoveation=t)};let L=null;const D=new IF;D.setAnimationLoop(function(e,s){if(h=s.getViewerPose(l||r),p=s,null!==h){const e=h.views;null!==u&&(t.setRenderTargetFramebuffer(_,u.framebuffer),t.setRenderTarget(_));let i=!1;e.length!==T.cameras.length&&(T.cameras.length=0,i=!0);for(let s=0;s<e.length;s++){const n=e[s];let r=null;if(null!==u)r=u.getViewport(n);else{const e=c.getViewSubImage(d,n);r=e.viewport,0===s&&(t.setRenderTargetTextures(_,e.colorTexture,d.ignoreDepthValues?void 0:e.depthStencilTexture),t.setRenderTarget(_))}let a=x[s];void 0===a&&(a=new xF,a.layers.enable(s),a.viewport=new aO,x[s]=a),a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(n.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(r.x,r.y,r.width,r.height),0===s&&(T.matrix.copy(a.matrix),T.matrix.decompose(T.position,T.quaternion,T.scale)),!0===i&&T.cameras.push(a)}}for(let t=0;t<g.length;t++){const e=v[t],i=g[t];null!==e&&void 0!==i&&i.update(e,s,l||r)}L&&L(e,s),s.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:s}),p=null}),this.setAnimationLoop=function(t){L=t},this.dispose=function(){}}}function cz(t,e){function i(t,e){!0===t.matrixAutoUpdate&&t.updateMatrix(),e.value.copy(t.matrix)}function s(s,n){s.opacity.value=n.opacity,n.color&&s.diffuse.value.copy(n.color),n.emissive&&s.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(s.map.value=n.map,i(n.map,s.mapTransform)),n.alphaMap&&(s.alphaMap.value=n.alphaMap,i(n.alphaMap,s.alphaMapTransform)),n.bumpMap&&(s.bumpMap.value=n.bumpMap,i(n.bumpMap,s.bumpMapTransform),s.bumpScale.value=n.bumpScale,1===n.side&&(s.bumpScale.value*=-1)),n.normalMap&&(s.normalMap.value=n.normalMap,i(n.normalMap,s.normalMapTransform),s.normalScale.value.copy(n.normalScale),1===n.side&&s.normalScale.value.negate()),n.displacementMap&&(s.displacementMap.value=n.displacementMap,i(n.displacementMap,s.displacementMapTransform),s.displacementScale.value=n.displacementScale,s.displacementBias.value=n.displacementBias),n.emissiveMap&&(s.emissiveMap.value=n.emissiveMap,i(n.emissiveMap,s.emissiveMapTransform)),n.specularMap&&(s.specularMap.value=n.specularMap,i(n.specularMap,s.specularMapTransform)),n.alphaTest>0&&(s.alphaTest.value=n.alphaTest);const r=e.get(n).envMap;if(r&&(s.envMap.value=r,s.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,s.reflectivity.value=n.reflectivity,s.ior.value=n.ior,s.refractionRatio.value=n.refractionRatio),n.lightMap){s.lightMap.value=n.lightMap;const e=!0===t._useLegacyLights?Math.PI:1;s.lightMapIntensity.value=n.lightMapIntensity*e,i(n.lightMap,s.lightMapTransform)}n.aoMap&&(s.aoMap.value=n.aoMap,s.aoMapIntensity.value=n.aoMapIntensity,i(n.aoMap,s.aoMapTransform))}return{refreshFogUniforms:function(e,i){i.color.getRGB(e.fogColor.value,gF(t)),i.isFog?(e.fogNear.value=i.near,e.fogFar.value=i.far):i.isFogExp2&&(e.fogDensity.value=i.density)},refreshMaterialUniforms:function(t,n,r,a,o){n.isMeshBasicMaterial||n.isMeshLambertMaterial?s(t,n):n.isMeshToonMaterial?(s(t,n),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,n)):n.isMeshPhongMaterial?(s(t,n),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,n)):n.isMeshStandardMaterial?(s(t,n),function(t,s){t.metalness.value=s.metalness,s.metalnessMap&&(t.metalnessMap.value=s.metalnessMap,i(s.metalnessMap,t.metalnessMapTransform));t.roughness.value=s.roughness,s.roughnessMap&&(t.roughnessMap.value=s.roughnessMap,i(s.roughnessMap,t.roughnessMapTransform));const n=e.get(s).envMap;n&&(t.envMapIntensity.value=s.envMapIntensity)}(t,n),n.isMeshPhysicalMaterial&&function(t,e,s){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,i(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,i(e.sheenRoughnessMap,t.sheenRoughnessMapTransform)));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,i(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,i(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,i(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),1===e.side&&t.clearcoatNormalScale.value.negate()));e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,i(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,i(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform)));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=s.texture,t.transmissionSamplerSize.value.set(s.width,s.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,i(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,i(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,i(e.anisotropyMap,t.anisotropyMapTransform)));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,i(e.specularColorMap,t.specularColorMapTransform));e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,i(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,n,o)):n.isMeshMatcapMaterial?(s(t,n),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,n)):n.isMeshDepthMaterial?s(t,n):n.isMeshDistanceMaterial?(s(t,n),function(t,i){const s=e.get(i).light;t.referencePosition.value.setFromMatrixPosition(s.matrixWorld),t.nearDistance.value=s.shadow.camera.near,t.farDistance.value=s.shadow.camera.far}(t,n)):n.isMeshNormalMaterial?s(t,n):n.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,i(e.map,t.mapTransform))}(t,n),n.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,n)):n.isPointsMaterial?function(t,e,s,n){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*s,t.scale.value=.5*n,e.map&&(t.map.value=e.map,i(e.map,t.uvTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,i(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,n,r,a):n.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,i(e.map,t.mapTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,i(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,n):n.isShadowMaterial?(t.color.value.copy(n.color),t.opacity.value=n.opacity):n.isShaderMaterial&&(n.uniformsNeedUpdate=!1)}}}function dz(t,e,i,s){let n={},r={},a=[];const o=i.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function l(t,e,i){const s=t.value;if(void 0===i[e]){if("number"==typeof s)i[e]=s;else{const t=Array.isArray(s)?s:[s],n=[];for(let e=0;e<t.length;e++)n.push(t[e].clone());i[e]=n}return!0}if("number"==typeof s){if(i[e]!==s)return i[e]=s,!0}else{const t=Array.isArray(i[e])?i[e]:[i[e]],n=Array.isArray(s)?s:[s];for(let e=0;e<t.length;e++){const i=t[e];if(!1===i.equals(n[e]))return i.copy(n[e]),!0}}return!1}function h(t){const e={boundary:0,storage:0};return"number"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture,e}function c(e){const i=e.target;i.removeEventListener("dispose",c);const s=a.indexOf(i.__bindingPointIndex);a.splice(s,1),t.deleteBuffer(n[i.id]),delete n[i.id],delete r[i.id]}return{bind:function(t,e){const i=e.program;s.uniformBlockBinding(t,i)},update:function(i,d){let u=n[i.id];void 0===u&&(!function(t){const e=t.uniforms;let i=0;const s=16;let n=0;for(let t=0,r=e.length;t<r;t++){const r=e[t],a={boundary:0,storage:0},o=Array.isArray(r.value)?r.value:[r.value];for(let t=0,e=o.length;t<e;t++){const e=h(o[t]);a.boundary+=e.boundary,a.storage+=e.storage}if(r.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),r.__offset=i,t>0){n=i%s;0!==n&&s-n-a.boundary<0&&(i+=s-n,r.__offset=i)}i+=a.storage}n=i%s,n>0&&(i+=s-n);t.__size=i,t.__cache={}}(i),u=function(e){const i=function(){for(let t=0;t<o;t++)if(-1===a.indexOf(t))return a.push(t),t;return 0}();e.__bindingPointIndex=i;const s=t.createBuffer(),n=e.__size,r=e.usage;return t.bindBuffer(t.UNIFORM_BUFFER,s),t.bufferData(t.UNIFORM_BUFFER,n,r),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,i,s),s}(i),n[i.id]=u,i.addEventListener("dispose",c));const p=d.program;s.updateUBOMapping(i,p);const f=e.render.frame;r[i.id]!==f&&(!function(e){const i=n[e.id],s=e.uniforms,r=e.__cache;t.bindBuffer(t.UNIFORM_BUFFER,i);for(let e=0,i=s.length;e<i;e++){const i=s[e];if(!0===l(i,e,r)){const e=i.__offset,s=Array.isArray(i.value)?i.value:[i.value];let n=0;for(let r=0;r<s.length;r++){const a=s[r],o=h(a);"number"==typeof a?(i.__data[0]=a,t.bufferSubData(t.UNIFORM_BUFFER,e+n,i.__data)):a.isMatrix3?(i.__data[0]=a.elements[0],i.__data[1]=a.elements[1],i.__data[2]=a.elements[2],i.__data[3]=a.elements[0],i.__data[4]=a.elements[3],i.__data[5]=a.elements[4],i.__data[6]=a.elements[5],i.__data[7]=a.elements[0],i.__data[8]=a.elements[6],i.__data[9]=a.elements[7],i.__data[10]=a.elements[8],i.__data[11]=a.elements[0]):(a.toArray(i.__data,n),n+=o.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,e,i.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}(i),r[i.id]=f)},dispose:function(){for(const e in n)t.deleteBuffer(n[e]);a=[],n={},r={}}}}class uz{constructor(t={}){const{canvas:e=GI(),context:i=null,depth:s=!0,stencil:n=!0,alpha:r=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:c=!1}=t;let d;this.isWebGLRenderer=!0,d=null!==i?i.getContextAttributes().alpha:r;const u=new Uint32Array(4),p=new Int32Array(4);let f=null,m=null;const _=[],g=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=aI,this._useLegacyLights=!1,this.toneMapping=0,this.toneMappingExposure=1;const v=this;let y=!1,S=0,x=0,T=null,E=-1,b=null;const w=new aO,A=new aO;let C=null;const M=new DN(0);let P=0,R=e.width,L=e.height,D=1,I=null,O=null;const N=new aO(0,0,R,L),F=new aO(0,0,R,L);let U=!1;const B=new DF;let z=!1,k=!1,V=null;const H=new HO,G=new BI,W=new uO,X={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Y(){return null===T?D:1}let q,j,$,K,Z,Q,J,tt,et,it,st,nt,rt,at,ot,lt,ht,ct,dt,ut,pt,ft,mt,_t,gt=i;function vt(t,i){for(let s=0;s<t.length;s++){const n=t[s],r=e.getContext(n,i);if(null!==r)return r}return null}try{const t={alpha:!0,depth:s,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:c};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${pD}`),e.addEventListener("webglcontextlost",xt,!1),e.addEventListener("webglcontextrestored",Tt,!1),e.addEventListener("webglcontextcreationerror",Et,!1),null===gt){const e=["webgl2","webgl","experimental-webgl"];if(!0===v.isWebGL1Renderer&&e.shift(),gt=vt(e,t),null===gt)throw vt(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}"undefined"!=typeof WebGLRenderingContext&&WebGLRenderingContext,void 0===gt.getShaderPrecisionFormat&&(gt.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(t){throw t}function yt(){q=new lU(gt),j=new GF(gt,q,t),q.init(j),ft=new sz(gt,q,j),$=new ez(gt,q,j),K=new dU(gt),Z=new VB,Q=new iz(gt,q,$,Z,j,ft,K),J=new XF(v),tt=new oU(v),et=new OF(gt,j),mt=new VF(gt,q,et,j),it=new hU(gt,et,K,mt),st=new mU(gt,it,et,K),dt=new fU(gt,j,Q),lt=new WF(Z),nt=new kB(v,J,tt,q,j,mt,lt),rt=new cz(v,Z),at=new XB,ot=new ZB(q,j),ct=new kF(v,J,tt,$,st,d,o),ht=new tz(v,st,j),_t=new dz(gt,K,j,$),ut=new HF(gt,q,K,j),pt=new cU(gt,q,K,j),K.programs=nt.programs,v.capabilities=j,v.extensions=q,v.properties=Z,v.renderLists=at,v.shadowMap=ht,v.state=$,v.info=K}yt();const St=new hz(v,gt);function xt(t){t.preventDefault(),y=!0}function Tt(){y=!1;const t=K.autoReset,e=ht.enabled,i=ht.autoUpdate,s=ht.needsUpdate,n=ht.type;yt(),K.autoReset=t,ht.enabled=e,ht.autoUpdate=i,ht.needsUpdate=s,ht.type=n}function Et(t){}function bt(t){const e=t.target;e.removeEventListener("dispose",bt),function(t){(function(t){const e=Z.get(t).programs;void 0!==e&&(e.forEach(function(t){nt.releaseProgram(t)}),t.isShaderMaterial&&nt.releaseShaderCache(t))})(t),Z.remove(t)}(e)}this.xr=St,this.getContext=function(){return gt},this.getContextAttributes=function(){return gt.getContextAttributes()},this.forceContextLoss=function(){const t=q.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=q.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return D},this.setPixelRatio=function(t){void 0!==t&&(D=t,this.setSize(R,L,!1))},this.getSize=function(t){return t.set(R,L)},this.setSize=function(t,i,s=!0){St.isPresenting||(R=t,L=i,e.width=Math.floor(t*D),e.height=Math.floor(i*D),!0===s&&(e.style.width=t+"px",e.style.height=i+"px"),this.setViewport(0,0,t,i))},this.getDrawingBufferSize=function(t){return t.set(R*D,L*D).floor()},this.setDrawingBufferSize=function(t,i,s){R=t,L=i,D=s,e.width=Math.floor(t*s),e.height=Math.floor(i*s),this.setViewport(0,0,t,i)},this.getCurrentViewport=function(t){return t.copy(w)},this.getViewport=function(t){return t.copy(N)},this.setViewport=function(t,e,i,s){t.isVector4?N.set(t.x,t.y,t.z,t.w):N.set(t,e,i,s),$.viewport(w.copy(N).multiplyScalar(D).floor())},this.getScissor=function(t){return t.copy(F)},this.setScissor=function(t,e,i,s){t.isVector4?F.set(t.x,t.y,t.z,t.w):F.set(t,e,i,s),$.scissor(A.copy(F).multiplyScalar(D).floor())},this.getScissorTest=function(){return U},this.setScissorTest=function(t){$.setScissorTest(U=t)},this.setOpaqueSort=function(t){I=t},this.setTransparentSort=function(t){O=t},this.getClearColor=function(t){return t.copy(ct.getClearColor())},this.setClearColor=function(){ct.setClearColor.apply(ct,arguments)},this.getClearAlpha=function(){return ct.getClearAlpha()},this.setClearAlpha=function(){ct.setClearAlpha.apply(ct,arguments)},this.clear=function(t=!0,e=!0,i=!0){let s=0;if(t){let t=!1;if(null!==T){const e=T.texture.format;t=1033===e||1031===e||1029===e}if(t){const t=T.texture.type,e=t===GD||t===YD||t===WD||t===$D||1017===t||1018===t,i=ct.getClearColor(),s=ct.getClearAlpha(),n=i.r,r=i.g,a=i.b;e?(u[0]=n,u[1]=r,u[2]=a,u[3]=s,gt.clearBufferuiv(gt.COLOR,0,u)):(p[0]=n,p[1]=r,p[2]=a,p[3]=s,gt.clearBufferiv(gt.COLOR,0,p))}else s|=gt.COLOR_BUFFER_BIT}e&&(s|=gt.DEPTH_BUFFER_BIT),i&&(s|=gt.STENCIL_BUFFER_BIT),gt.clear(s)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",xt,!1),e.removeEventListener("webglcontextrestored",Tt,!1),e.removeEventListener("webglcontextcreationerror",Et,!1),at.dispose(),ot.dispose(),Z.dispose(),J.dispose(),tt.dispose(),st.dispose(),mt.dispose(),_t.dispose(),nt.dispose(),St.dispose(),St.removeEventListener("sessionstart",At),St.removeEventListener("sessionend",Ct),V&&(V.dispose(),V=null),Mt.stop()},this.renderBufferDirect=function(t,e,i,s,n,r){null===e&&(e=X);const a=n.isMesh&&n.matrixWorld.determinant()<0,o=function(t,e,i,s,n){!0!==e.isScene&&(e=X);Q.resetTextureUnits();const r=e.fog,a=s.isMeshStandardMaterial?e.environment:null,o=null===T?v.outputColorSpace:!0===T.isXRRenderTarget?T.texture.colorSpace:oI,l=(s.isMeshStandardMaterial?tt:J).get(s.envMap||a),h=!0===s.vertexColors&&!!i.attributes.color&&4===i.attributes.color.itemSize,c=!!i.attributes.tangent&&(!!s.normalMap||s.anisotropy>0),d=!!i.morphAttributes.position,u=!!i.morphAttributes.normal,p=!!i.morphAttributes.color;let f=0;s.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(f=v.toneMapping));const _=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,g=void 0!==_?_.length:0,y=Z.get(s),S=m.state.lights;if(!0===z&&(!0===k||t!==b)){const e=t===b&&s.id===E;lt.setState(s,t,e)}let x=!1;s.version===y.__version?y.needsLights&&y.lightsStateVersion!==S.state.version||y.outputColorSpace!==o||n.isInstancedMesh&&!1===y.instancing?x=!0:n.isInstancedMesh||!0!==y.instancing?n.isSkinnedMesh&&!1===y.skinning?x=!0:n.isSkinnedMesh||!0!==y.skinning?n.isInstancedMesh&&!0===y.instancingColor&&null===n.instanceColor||n.isInstancedMesh&&!1===y.instancingColor&&null!==n.instanceColor||y.envMap!==l||!0===s.fog&&y.fog!==r?x=!0:void 0===y.numClippingPlanes||y.numClippingPlanes===lt.numPlanes&&y.numIntersection===lt.numIntersection?(y.vertexAlphas!==h||y.vertexTangents!==c||y.morphTargets!==d||y.morphNormals!==u||y.morphColors!==p||y.toneMapping!==f||!0===j.isWebGL2&&y.morphTargetsCount!==g)&&(x=!0):x=!0:x=!0:x=!0:(x=!0,y.__version=s.version);let w=y.currentProgram;!0===x&&(w=It(s,e,n));let A=!1,C=!1,M=!1;const P=w.getUniforms(),R=y.uniforms;$.useProgram(w.program)&&(A=!0,C=!0,M=!0);s.id!==E&&(E=s.id,C=!0);if(A||b!==t){P.setValue(gt,"projectionMatrix",t.projectionMatrix),P.setValue(gt,"viewMatrix",t.matrixWorldInverse);const e=P.map.cameraPosition;void 0!==e&&e.setValue(gt,W.setFromMatrixPosition(t.matrixWorld)),j.logarithmicDepthBuffer&&P.setValue(gt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(s.isMeshPhongMaterial||s.isMeshToonMaterial||s.isMeshLambertMaterial||s.isMeshBasicMaterial||s.isMeshStandardMaterial||s.isShaderMaterial)&&P.setValue(gt,"isOrthographic",!0===t.isOrthographicCamera),b!==t&&(b=t,C=!0,M=!0)}if(n.isSkinnedMesh){P.setOptional(gt,n,"bindMatrix"),P.setOptional(gt,n,"bindMatrixInverse");const t=n.skeleton;t&&j.floatVertexTextures&&(null===t.boneTexture&&t.computeBoneTexture(),P.setValue(gt,"boneTexture",t.boneTexture,Q),P.setValue(gt,"boneTextureSize",t.boneTextureSize))}const I=i.morphAttributes;(void 0!==I.position||void 0!==I.normal||void 0!==I.color&&!0===j.isWebGL2)&&dt.update(n,i,w);(C||y.receiveShadow!==n.receiveShadow)&&(y.receiveShadow=n.receiveShadow,P.setValue(gt,"receiveShadow",n.receiveShadow));s.isMeshGouraudMaterial&&null!==s.envMap&&(R.envMap.value=l,R.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);C&&(P.setValue(gt,"toneMappingExposure",v.toneMappingExposure),y.needsLights&&(N=M,(O=R).ambientLightColor.needsUpdate=N,O.lightProbe.needsUpdate=N,O.directionalLights.needsUpdate=N,O.directionalLightShadows.needsUpdate=N,O.pointLights.needsUpdate=N,O.pointLightShadows.needsUpdate=N,O.spotLights.needsUpdate=N,O.spotLightShadows.needsUpdate=N,O.rectAreaLights.needsUpdate=N,O.hemisphereLights.needsUpdate=N),r&&!0===s.fog&&rt.refreshFogUniforms(R,r),rt.refreshMaterialUniforms(R,s,D,L,V),yB.upload(gt,y.uniformsList,R,Q));var O,N;s.isShaderMaterial&&!0===s.uniformsNeedUpdate&&(yB.upload(gt,y.uniformsList,R,Q),s.uniformsNeedUpdate=!1);s.isSpriteMaterial&&P.setValue(gt,"center",n.center);if(P.setValue(gt,"modelViewMatrix",n.modelViewMatrix),P.setValue(gt,"normalMatrix",n.normalMatrix),P.setValue(gt,"modelMatrix",n.matrixWorld),s.isShaderMaterial||s.isRawShaderMaterial){const t=s.uniformsGroups;for(let e=0,i=t.length;e<i;e++)if(j.isWebGL2){const i=t[e];_t.update(i,w),_t.bind(i,w)}}return w}(t,e,i,s,n);$.setMaterial(s,a);let l=i.index,h=1;if(!0===s.wireframe){if(l=it.getWireframeAttribute(i),void 0===l)return;h=2}const c=i.drawRange,d=i.attributes.position;let u=c.start*h,p=(c.start+c.count)*h;null!==r&&(u=Math.max(u,r.start*h),p=Math.min(p,(r.start+r.count)*h)),null!==l?(u=Math.max(u,0),p=Math.min(p,l.count)):null!=d&&(u=Math.max(u,0),p=Math.min(p,d.count));const f=p-u;if(f<0||f===1/0)return;let _;mt.setup(n,s,o,i,l);let g=ut;if(null!==l&&(_=et.get(l),g=pt,g.setIndex(_)),n.isMesh)!0===s.wireframe?($.setLineWidth(s.wireframeLinewidth*Y()),g.setMode(gt.LINES)):g.setMode(gt.TRIANGLES);else if(n.isLine){let t=s.linewidth;void 0===t&&(t=1),$.setLineWidth(t*Y()),n.isLineSegments?g.setMode(gt.LINES):n.isLineLoop?g.setMode(gt.LINE_LOOP):g.setMode(gt.LINE_STRIP)}else n.isPoints?g.setMode(gt.POINTS):n.isSprite&&g.setMode(gt.TRIANGLES);if(n.isInstancedMesh)g.renderInstances(u,f,n.count);else if(i.isInstancedBufferGeometry){const t=void 0!==i._maxInstanceCount?i._maxInstanceCount:1/0,e=Math.min(i.instanceCount,t);g.renderInstances(u,f,e)}else g.render(u,f)},this.compile=function(t,e){function i(t,e,i){!0===t.transparent&&2===t.side&&!1===t.forceSinglePass?(t.side=1,t.needsUpdate=!0,It(t,e,i),t.side=0,t.needsUpdate=!0,It(t,e,i),t.side=2):It(t,e,i)}m=ot.get(t),m.init(),g.push(m),t.traverseVisible(function(t){t.isLight&&t.layers.test(e.layers)&&(m.pushLight(t),t.castShadow&&m.pushShadow(t))}),m.setupLights(v._useLegacyLights),t.traverse(function(e){const s=e.material;if(s)if(Array.isArray(s))for(let n=0;n<s.length;n++){i(s[n],t,e)}else i(s,t,e)}),g.pop(),m=null};let wt=null;function At(){Mt.stop()}function Ct(){Mt.start()}const Mt=new IF;function Pt(t,e,i,s){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)i=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)m.pushLight(t),t.castShadow&&m.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||B.intersectsSprite(t)){s&&W.setFromMatrixPosition(t.matrixWorld).applyMatrix4(H);const e=st.update(t),n=t.material;n.visible&&f.push(t,e,n,i,W.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||B.intersectsObject(t))){const e=st.update(t),n=t.material;if(s&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),W.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),W.copy(e.boundingSphere.center)),W.applyMatrix4(t.matrixWorld).applyMatrix4(H)),Array.isArray(n)){const s=e.groups;for(let r=0,a=s.length;r<a;r++){const a=s[r],o=n[a.materialIndex];o&&o.visible&&f.push(t,e,o,i,W.z,a)}}else n.visible&&f.push(t,e,n,i,W.z,null)}const n=t.children;for(let t=0,r=n.length;t<r;t++)Pt(n[t],e,i,s)}function Rt(t,e,i,s){const n=t.opaque,r=t.transmissive,a=t.transparent;m.setupLightsView(i),!0===z&<.setGlobalState(v.clippingPlanes,i),r.length>0&&function(t,e,i,s){const n=j.isWebGL2;null===V&&(V=new lO(1,1,{generateMipmaps:!0,type:q.has("EXT_color_buffer_half_float")?jD:GD,minFilter:HD,samples:n?4:0}));v.getDrawingBufferSize(G),n?V.setSize(G.x,G.y):V.setSize(NI(G.x),NI(G.y));const r=v.getRenderTarget();v.setRenderTarget(V),v.getClearColor(M),P=v.getClearAlpha(),P<1&&v.setClearColor(16777215,.5);v.clear();const a=v.toneMapping;v.toneMapping=0,Lt(t,i,s),Q.updateMultisampleRenderTarget(V),Q.updateRenderTargetMipmap(V);let o=!1;for(let t=0,n=e.length;t<n;t++){const n=e[t],r=n.object,a=n.geometry,l=n.material,h=n.group;if(2===l.side&&r.layers.test(s.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,Dt(r,i,s,a,l,h),l.side=t,l.needsUpdate=!0,o=!0}}!0===o&&(Q.updateMultisampleRenderTarget(V),Q.updateRenderTargetMipmap(V));v.setRenderTarget(r),v.setClearColor(M,P),v.toneMapping=a}(n,r,e,i),s&&$.viewport(w.copy(s)),n.length>0&&Lt(n,e,i),r.length>0&&Lt(r,e,i),a.length>0&&Lt(a,e,i),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function Lt(t,e,i){const s=!0===e.isScene?e.overrideMaterial:null;for(let n=0,r=t.length;n<r;n++){const r=t[n],a=r.object,o=r.geometry,l=null===s?r.material:s,h=r.group;a.layers.test(i.layers)&&Dt(a,e,i,o,l,h)}}function Dt(t,e,i,s,n,r){t.onBeforeRender(v,e,i,s,n,r),t.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix),n.onBeforeRender(v,e,i,s,t,r),!0===n.transparent&&2===n.side&&!1===n.forceSinglePass?(n.side=1,n.needsUpdate=!0,v.renderBufferDirect(i,e,s,n,t,r),n.side=0,n.needsUpdate=!0,v.renderBufferDirect(i,e,s,n,t,r),n.side=2):v.renderBufferDirect(i,e,s,n,t,r),t.onAfterRender(v,e,i,s,n,r)}function It(t,e,i){!0!==e.isScene&&(e=X);const s=Z.get(t),n=m.state.lights,r=m.state.shadowsArray,a=n.state.version,o=nt.getParameters(t,n.state,r,e,i),l=nt.getProgramCacheKey(o);let h=s.programs;s.environment=t.isMeshStandardMaterial?e.environment:null,s.fog=e.fog,s.envMap=(t.isMeshStandardMaterial?tt:J).get(t.envMap||s.environment),void 0===h&&(t.addEventListener("dispose",bt),h=new Map,s.programs=h);let c=h.get(l);if(void 0!==c){if(s.currentProgram===c&&s.lightsStateVersion===a)return Ot(t,o),c}else o.uniforms=nt.getUniforms(t),t.onBuild(i,o,v),t.onBeforeCompile(o,v),c=nt.acquireProgram(o,l),h.set(l,c),s.uniforms=o.uniforms;const d=s.uniforms;(t.isShaderMaterial||t.isRawShaderMaterial)&&!0!==t.clipping||(d.clippingPlanes=lt.uniform),Ot(t,o),s.needsLights=function(t){return t.isMeshLambertMaterial||t.isMeshToonMaterial||t.isMeshPhongMaterial||t.isMeshStandardMaterial||t.isShadowMaterial||t.isShaderMaterial&&!0===t.lights}(t),s.lightsStateVersion=a,s.needsLights&&(d.ambientLightColor.value=n.state.ambient,d.lightProbe.value=n.state.probe,d.directionalLights.value=n.state.directional,d.directionalLightShadows.value=n.state.directionalShadow,d.spotLights.value=n.state.spot,d.spotLightShadows.value=n.state.spotShadow,d.rectAreaLights.value=n.state.rectArea,d.ltc_1.value=n.state.rectAreaLTC1,d.ltc_2.value=n.state.rectAreaLTC2,d.pointLights.value=n.state.point,d.pointLightShadows.value=n.state.pointShadow,d.hemisphereLights.value=n.state.hemi,d.directionalShadowMap.value=n.state.directionalShadowMap,d.directionalShadowMatrix.value=n.state.directionalShadowMatrix,d.spotShadowMap.value=n.state.spotShadowMap,d.spotLightMatrix.value=n.state.spotLightMatrix,d.spotLightMap.value=n.state.spotLightMap,d.pointShadowMap.value=n.state.pointShadowMap,d.pointShadowMatrix.value=n.state.pointShadowMatrix);const u=c.getUniforms(),p=yB.seqWithValue(u.seq,d);return s.currentProgram=c,s.uniformsList=p,c}function Ot(t,e){const i=Z.get(t);i.outputColorSpace=e.outputColorSpace,i.instancing=e.instancing,i.instancingColor=e.instancingColor,i.skinning=e.skinning,i.morphTargets=e.morphTargets,i.morphNormals=e.morphNormals,i.morphColors=e.morphColors,i.morphTargetsCount=e.morphTargetsCount,i.numClippingPlanes=e.numClippingPlanes,i.numIntersection=e.numClipIntersection,i.vertexAlphas=e.vertexAlphas,i.vertexTangents=e.vertexTangents,i.toneMapping=e.toneMapping}Mt.setAnimationLoop(function(t){wt&&wt(t)}),"undefined"!=typeof self&&Mt.setContext(self),this.setAnimationLoop=function(t){wt=t,St.setAnimationLoop(t),null===t?Mt.stop():Mt.start()},St.addEventListener("sessionstart",At),St.addEventListener("sessionend",Ct),this.render=function(t,e){if(void 0!==e&&!0!==e.isCamera)return;if(!0===y)return;!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===St.enabled&&!0===St.isPresenting&&(!0===St.cameraAutoUpdate&&St.updateCamera(e),e=St.getCamera()),!0===t.isScene&&t.onBeforeRender(v,t,e,T),m=ot.get(t,g.length),m.init(),g.push(m),H.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),B.setFromProjectionMatrix(H),k=this.localClippingEnabled,z=lt.init(this.clippingPlanes,k),f=at.get(t,_.length),f.init(),_.push(f),Pt(t,e,0,v.sortObjects),f.finish(),!0===v.sortObjects&&f.sort(I,O),this.info.render.frame++,!0===z&<.beginShadows();const i=m.state.shadowsArray;if(ht.render(i,t,e),!0===z&<.endShadows(),!0===this.info.autoReset&&this.info.reset(),ct.render(f,t),m.setupLights(v._useLegacyLights),e.isArrayCamera){const i=e.cameras;for(let e=0,s=i.length;e<s;e++){const s=i[e];Rt(f,t,s,s.viewport)}}else Rt(f,t,e);null!==T&&(Q.updateMultisampleRenderTarget(T),Q.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(v,t,e),mt.resetDefaultState(),E=-1,b=null,g.pop(),m=g.length>0?g[g.length-1]:null,_.pop(),f=_.length>0?_[_.length-1]:null},this.getActiveCubeFace=function(){return S},this.getActiveMipmapLevel=function(){return x},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,i){Z.get(t.texture).__webglTexture=e,Z.get(t.depthTexture).__webglTexture=i;const s=Z.get(t);s.__hasExternalTextures=!0,s.__hasExternalTextures&&(s.__autoAllocateDepthBuffer=void 0===i,s.__autoAllocateDepthBuffer||!0===q.has("WEBGL_multisampled_render_to_texture")&&(s.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(t,e){const i=Z.get(t);i.__webglFramebuffer=e,i.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,i=0){T=t,S=e,x=i;let s=!0,n=null,r=!1,a=!1;if(t){const o=Z.get(t);void 0!==o.__useDefaultFramebuffer?($.bindFramebuffer(gt.FRAMEBUFFER,null),s=!1):void 0===o.__webglFramebuffer?Q.setupRenderTarget(t):o.__hasExternalTextures&&Q.rebindTextures(t,Z.get(t.texture).__webglTexture,Z.get(t.depthTexture).__webglTexture);const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const h=Z.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(n=Array.isArray(h[e])?h[e][i]:h[e],r=!0):n=j.isWebGL2&&t.samples>0&&!1===Q.useMultisampledRTT(t)?Z.get(t).__webglMultisampledFramebuffer:Array.isArray(h)?h[i]:h,w.copy(t.viewport),A.copy(t.scissor),C=t.scissorTest}else w.copy(N).multiplyScalar(D).floor(),A.copy(F).multiplyScalar(D).floor(),C=U;if($.bindFramebuffer(gt.FRAMEBUFFER,n)&&j.drawBuffers&&s&&$.drawBuffers(t,n),$.viewport(w),$.scissor(A),$.setScissorTest(C),r){const s=Z.get(t.texture);gt.framebufferTexture2D(gt.FRAMEBUFFER,gt.COLOR_ATTACHMENT0,gt.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.__webglTexture,i)}else if(a){const s=Z.get(t.texture),n=e||0;gt.framebufferTextureLayer(gt.FRAMEBUFFER,gt.COLOR_ATTACHMENT0,s.__webglTexture,i||0,n)}E=-1},this.readRenderTargetPixels=function(t,e,i,s,n,r,a){if(!t||!t.isWebGLRenderTarget)return;let o=Z.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){$.bindFramebuffer(gt.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(o!==KD&&ft.convert(o)!==gt.getParameter(gt.IMPLEMENTATION_COLOR_READ_FORMAT))return;const h=l===jD&&(q.has("EXT_color_buffer_half_float")||j.isWebGL2&&q.has("EXT_color_buffer_float"));if(!(l===GD||ft.convert(l)===gt.getParameter(gt.IMPLEMENTATION_COLOR_READ_TYPE)||l===qD&&(j.isWebGL2||q.has("OES_texture_float")||q.has("WEBGL_color_buffer_float"))||h))return;e>=0&&e<=t.width-s&&i>=0&&i<=t.height-n&>.readPixels(e,i,s,n,ft.convert(o),ft.convert(l),r)}finally{const t=null!==T?Z.get(T).__webglFramebuffer:null;$.bindFramebuffer(gt.FRAMEBUFFER,t)}}},this.copyFramebufferToTexture=function(t,e,i=0){const s=Math.pow(2,-i),n=Math.floor(e.image.width*s),r=Math.floor(e.image.height*s);Q.setTexture2D(e,0),gt.copyTexSubImage2D(gt.TEXTURE_2D,i,0,0,t.x,t.y,n,r),$.unbindTexture()},this.copyTextureToTexture=function(t,e,i,s=0){const n=e.image.width,r=e.image.height,a=ft.convert(i.format),o=ft.convert(i.type);Q.setTexture2D(i,0),gt.pixelStorei(gt.UNPACK_FLIP_Y_WEBGL,i.flipY),gt.pixelStorei(gt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),gt.pixelStorei(gt.UNPACK_ALIGNMENT,i.unpackAlignment),e.isDataTexture?gt.texSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,n,r,a,o,e.image.data):e.isCompressedTexture?gt.compressedTexSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,e.mipmaps[0].width,e.mipmaps[0].height,a,e.mipmaps[0].data):gt.texSubImage2D(gt.TEXTURE_2D,s,t.x,t.y,a,o,e.image),0===s&&i.generateMipmaps&>.generateMipmap(gt.TEXTURE_2D),$.unbindTexture()},this.copyTextureToTexture3D=function(t,e,i,s,n=0){if(v.isWebGL1Renderer)return;const r=t.max.x-t.min.x+1,a=t.max.y-t.min.y+1,o=t.max.z-t.min.z+1,l=ft.convert(s.format),h=ft.convert(s.type);let c;if(s.isData3DTexture)Q.setTexture3D(s,0),c=gt.TEXTURE_3D;else{if(!s.isDataArrayTexture)return;Q.setTexture2DArray(s,0),c=gt.TEXTURE_2D_ARRAY}gt.pixelStorei(gt.UNPACK_FLIP_Y_WEBGL,s.flipY),gt.pixelStorei(gt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,s.premultiplyAlpha),gt.pixelStorei(gt.UNPACK_ALIGNMENT,s.unpackAlignment);const d=gt.getParameter(gt.UNPACK_ROW_LENGTH),u=gt.getParameter(gt.UNPACK_IMAGE_HEIGHT),p=gt.getParameter(gt.UNPACK_SKIP_PIXELS),f=gt.getParameter(gt.UNPACK_SKIP_ROWS),m=gt.getParameter(gt.UNPACK_SKIP_IMAGES),_=i.isCompressedTexture?i.mipmaps[0]:i.image;gt.pixelStorei(gt.UNPACK_ROW_LENGTH,_.width),gt.pixelStorei(gt.UNPACK_IMAGE_HEIGHT,_.height),gt.pixelStorei(gt.UNPACK_SKIP_PIXELS,t.min.x),gt.pixelStorei(gt.UNPACK_SKIP_ROWS,t.min.y),gt.pixelStorei(gt.UNPACK_SKIP_IMAGES,t.min.z),i.isDataTexture||i.isData3DTexture?gt.texSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,h,_.data):i.isCompressedArrayTexture?gt.compressedTexSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,_.data):gt.texSubImage3D(c,n,e.x,e.y,e.z,r,a,o,l,h,_),gt.pixelStorei(gt.UNPACK_ROW_LENGTH,d),gt.pixelStorei(gt.UNPACK_IMAGE_HEIGHT,u),gt.pixelStorei(gt.UNPACK_SKIP_PIXELS,p),gt.pixelStorei(gt.UNPACK_SKIP_ROWS,f),gt.pixelStorei(gt.UNPACK_SKIP_IMAGES,m),0===n&&s.generateMipmaps&>.generateMipmap(c),$.unbindTexture()},this.initTexture=function(t){t.isCubeTexture?Q.setTextureCube(t,0):t.isData3DTexture?Q.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?Q.setTexture2DArray(t,0):Q.setTexture2D(t,0),$.unbindTexture()},this.resetState=function(){S=0,x=0,T=null,$.reset(),mt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return wI}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===lI?"display-p3":"srgb",e.unpackColorSpace=KI.workingColorSpace===hI?"display-p3":"srgb"}get physicallyCorrectLights(){return!this.useLegacyLights}set physicallyCorrectLights(t){this.useLegacyLights=!t}get outputEncoding(){return this.outputColorSpace===aI?nI:3e3}set outputEncoding(t){this.outputColorSpace=t===nI?aI:oI}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(t){this._useLegacyLights=t}}(class extends uz{}).prototype.isWebGL1Renderer=!0;let pz=class extends pN{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e}};class fz extends CN{constructor(t){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new DN(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 DN(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new BI(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class mz extends pN{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new DN(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),e}}const _z=new HO,gz=new uO,vz=new uO;class yz{constructor(t){this.camera=t,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new BI(512,512),this.map=null,this.mapPass=null,this.matrix=new HO,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new DF,this._frameExtents=new BI(1,1),this._viewportCount=1,this._viewports=[new aO(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,i=this.matrix;gz.setFromMatrixPosition(t.matrixWorld),e.position.copy(gz),vz.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(vz),e.updateMatrixWorld(),_z.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(_z),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(_z)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Sz extends yz{constructor(){super(new YF(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class xz extends mz{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(pN.DEFAULT_UP),this.updateMatrix(),this.target=new pN,this.shadow=new Sz}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class Tz extends mz{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:pD}})),"undefined"!=typeof window&&(window.__THREE__||(window.__THREE__=pD));class Ez{constructor(t){this.scene=null,this.camera=null,this.renderer=null,this.cube=null,this.directionalLight=null,this.ambientLight=null,this.canvas=null,this.initialized=!1,this.visible=!0,this.animationFrameId=null,this.needsRender=!1,this.resizeObserver=null}initialize(t){try{this.canvas=t,this.scene=new pz,this.scene.background=null;const e=t.clientWidth||t.width,i=e/(t.clientHeight||t.height)||1,s=4.5;this.camera=new YF(s*i/-2,s*i/2,s/2,s/-2,.1,1e3),this.camera.position.set(5,0,0),this.camera.lookAt(0,0,0),this.camera.updateProjectionMatrix(),this.renderer=new uz({canvas:t,alpha:!0,antialias:!0});const n=t.clientWidth||t.width,r=t.clientHeight||t.height;if(this.renderer.setSize(n,r,!1),this.renderer.setPixelRatio(window.devicePixelRatio||1),!this.renderer.getContext())throw new Error("Failed to create WebGL context");const a=new fF(1,1,1),o=new fz({color:11184810,metalness:.7,roughness:.3,emissive:1710623,emissiveIntensity:.1});this.cube=new uF(a,o),this.cube.position.set(0,0,0),this.scene.add(this.cube),this.directionalLight=new xz(16777215,2.2),this.directionalLight.position.set(2,3,2),this.scene.add(this.directionalLight);const l=new xz(16777215,.8);l.position.set(-1,.5,-1),this.scene.add(l);const h=new xz(16777215,1.2);h.position.set(-2,-1.5,2),this.scene.add(h);const c=new xz(16777215,1.2);c.position.set(2,-1.5,2),this.scene.add(c);const d=new xz(16777215,.4);d.position.set(0,-1,-2),this.scene.add(d),this.ambientLight=new Tz(13421789,.35),this.scene.add(this.ambientLight),this.setupResizeObserver(),this.requestRender(),this.initialized=!0}catch(t){throw this.initialized=!1,this.cleanup(),t}}setRotation(t,e){if(!this.initialized||!this.camera)return;if(!isFinite(t)||!isFinite(e))return;const i=t*(Math.PI/180),s=e*(Math.PI/180),n=5*Math.sin(s)*Math.cos(i),r=5*Math.sin(i),a=5*Math.cos(s)*Math.cos(i);this.camera.position.set(n,r,a),this.camera.lookAt(0,0,0),this.requestRender()}setVisible(t){this.visible=t,this.canvas&&(this.canvas.style.display=t?"block":"none",t&&this.initialized&&this.requestRender())}setupResizeObserver(){this.canvas&&(this.resizeObserver=new ResizeObserver(t=>{for(const e of t){const{width:t,height:i}=e.contentRect;this.onCanvasResize(t,i)}}),this.resizeObserver.observe(this.canvas))}onCanvasResize(t,e){if(!this.camera||!this.renderer)return;const i=t/e||1,s=4.5;this.camera.left=s*i/-2,this.camera.right=s*i/2,this.camera.top=2.25,this.camera.bottom=-2.25,this.camera.updateProjectionMatrix(),this.renderer.setSize(t,e,!1),this.requestRender()}requestRender(){this.needsRender||(this.needsRender=!0,this.animationFrameId=requestAnimationFrame(()=>{this.render(),this.needsRender=!1,this.animationFrameId=null}))}render(){this.initialized&&this.visible&&this.scene&&this.camera&&this.renderer&&this.renderer.render(this.scene,this.camera)}cleanup(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.needsRender=!1,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.cube&&(this.cube.geometry&&this.cube.geometry.dispose(),this.cube.material&&(Array.isArray(this.cube.material)?this.cube.material.forEach(t=>t.dispose()):this.cube.material.dispose()),this.cube=null),this.scene&&(this.scene.clear(),this.scene=null),this.renderer&&(this.renderer.dispose(),this.renderer=null),this.camera=null,this.directionalLight=null,this.ambientLight=null,this.canvas=null}destroy(){this.cleanup(),this.initialized=!1}isInitialized(){return this.initialized}isVisible(){return this.visible}}class bz{constructor(t,e){this.cubeEntity=null,this.cubeMaterial=null,this.cubeCamera=null,this.directionalLight=null,this.ambientLight=null,this.cubeRoot=null,this.initialized=!1,this.visible=!0,this.MIN_CANVAS_SIZE=200,this.MIN_PARENT_DIV_SIZE=100,this.cubeLayer=null,this.separateCanvas=null,this.parentDiv=null,this.resizeObserver=null,this.useParentDiv=!1,this.onResizeCallback=null,this.threeJsRenderer=null,this.useThreeJs=!1,this.mainApp=t,this.app=t,this.config=e,this.useParentDiv=!!e.parentElementId}initialize(){if(!this.initialized)try{this.useParentDiv&&this.config.parentElementId?this.initializeInParentDiv():this.initializeInMainCanvas(),this.initialized=!0}catch(t){throw this.cleanup(),t}}initializeInMainCanvas(){this.setupCubeLayer(),this.cubeRoot=new z_("NavigationCubeRoot"),this.app.root.addChild(this.cubeRoot),this.cubeMaterial=this.createCubeMaterial(),this.cubeEntity=this.createCubeGeometry(),this.cubeCamera=this.setupCubeCamera(),this.setupCubeLighting(),this.updateViewport()}initializeInParentDiv(){const t=this.config.parentElementId;if(this.parentDiv=document.getElementById(t),!this.parentDiv)return this.useParentDiv=!1,void this.initializeInMainCanvas();const e=this.parentDiv.querySelector("#navigation-cube-canvas");e&&e.remove(),this.separateCanvas=document.createElement("canvas"),this.separateCanvas.id="navigation-cube-canvas",this.separateCanvas.style.width="100%",this.separateCanvas.style.height="100%",this.separateCanvas.style.display="block",this.separateCanvas.style.position="absolute",this.separateCanvas.style.top="0",this.separateCanvas.style.left="0",this.parentDiv.appendChild(this.separateCanvas);const i=this.parentDiv.getBoundingClientRect();this.separateCanvas.width=Math.floor(i.width),this.separateCanvas.height=Math.floor(i.height);try{this.threeJsRenderer=new Ez(this.config),this.threeJsRenderer.initialize(this.separateCanvas),this.useThreeJs=!0,this.useParentDiv=!0}catch(t){return this.useParentDiv=!1,this.useThreeJs=!1,this.app=this.mainApp,void this.initializeInMainCanvas()}}setupCubeLayer(){this.cubeLayer=new iu({name:"NavigationCubeLayer",opaqueSortMode:0,transparentSortMode:0});this.app.scene.layers.push(this.cubeLayer)}createCubeGeometry(){const t=new z_("NavigationCube");return t.addComponent("render",{type:"box",material:this.cubeMaterial,castShadows:!1,receiveShadows:!1,layers:[this.cubeLayer.id]}),t.setLocalPosition(0,0,0),this.cubeRoot.addChild(t),t}createCubeMaterial(){const t=new Xf;return t.diffuse=new H(.6,.6,.65),t.metalness=.5,t.gloss=.5,t.useMetalness=!0,t.emissive=new H(.1,.1,.12),t.emissiveIntensity=.15,t.update(),t}setupCubeCamera(){const t=new z_("NavigationCubeCamera"),e=this.useParentDiv,i=new H(0,0,0,e?1:0);return t.addComponent("camera",{projection:1,orthoHeight:1.5,clearColor:i,clearColorBuffer:e,clearDepthBuffer:!0,priority:100,farClip:100,nearClip:.1,layers:[this.cubeLayer.id]}),t.setLocalPosition(0,0,5),t.lookAt(0,0,0),this.cubeRoot.addChild(t),t}setupCubeLighting(){this.directionalLight=new z_("CubeDirectionalLight");const t={type:"directional",color:new H(1,1,1),intensity:1.5,castShadows:!1};this.cubeLayer&&(t.layers=[this.cubeLayer.id]),this.directionalLight.addComponent("light",t),this.directionalLight.setLocalEulerAngles(45,45,0),this.cubeCamera.addChild(this.directionalLight),this.ambientLight=new z_("CubeAmbientLight");const e={type:"directional",color:new H(.8,.8,.85),intensity:.7,castShadows:!1};this.cubeLayer&&(e.layers=[this.cubeLayer.id]),this.ambientLight.addComponent("light",e),this.ambientLight.setLocalEulerAngles(-45,-135,0),this.cubeCamera.addChild(this.ambientLight)}setRotation(t,e){if(this.initialized)if(this.useThreeJs&&this.threeJsRenderer)this.threeJsRenderer.setRotation(t,e);else if(this.cubeCamera&&"number"==typeof t&&"number"==typeof e)try{const i=5,s=t*(Math.PI/180),n=e*(Math.PI/180),r=i*Math.sin(n)*Math.cos(s),a=i*Math.sin(s),o=i*Math.cos(n)*Math.cos(s);this.cubeCamera.setLocalPosition(r,a,o),this.cubeCamera.lookAt(0,0,0)}catch(t){}}render(){this.initialized&&this.visible&&this.useThreeJs}setVisible(t){this.visible=t,this.useThreeJs&&this.threeJsRenderer?this.threeJsRenderer.setVisible(t):this.initialized&&this.cubeRoot&&(this.cubeRoot.enabled=t)}isVisible(){return this.visible}updateSize(t){if("number"!=typeof t||!isFinite(t))return;const e=Math.max(50,Math.min(500,t));this.config.cubeSize=e,this.initialized&&this.cubeCamera&&this.updateViewport()}shouldShowCube(){if(this.useParentDiv&&this.parentDiv){const t=this.parentDiv.clientWidth,e=this.parentDiv.clientHeight;return t>=this.MIN_PARENT_DIV_SIZE&&e>=this.MIN_PARENT_DIV_SIZE}const t=this.app.graphicsDevice.canvas;if(!t)return!1;const e=t.width,i=t.height;return e>=this.MIN_CANVAS_SIZE&&i>=this.MIN_CANVAS_SIZE}updateViewport(){if(!this.cubeCamera||!this.cubeCamera.camera)return;const t=this.app.graphicsDevice.canvas;if(!t)return;const e=t.width,i=t.height;if(e<=0||i<=0)return;if(!this.shouldShowCube())return void(this.cubeRoot&&(this.cubeRoot.enabled=!1));this.cubeRoot&&!this.cubeRoot.enabled&&this.visible&&(this.cubeRoot.enabled=!0);const s=this.config.cubeSize;let n=s/e,r=s/i,a=1-n-this.config.padding.x/e,o=1-r-this.config.padding.y/i;a=Math.max(0,Math.min(a,1-n)),o=Math.max(0,Math.min(o,1-r)),n=Math.max(0,Math.min(n,1-a)),r=Math.max(0,Math.min(r,1-o)),this.cubeCamera.camera.rect=new J(a,o,n,r)}onCanvasResize(){this.initialized&&(this.updateViewport(),this.onResizeCallback&&this.onResizeCallback())}setResizeCallback(t){this.onResizeCallback=t}cleanup(){if(this.threeJsRenderer&&(this.threeJsRenderer.destroy(),this.threeJsRenderer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.ambientLight&&(this.ambientLight.destroy(),this.ambientLight=null),this.directionalLight&&(this.directionalLight.destroy(),this.directionalLight=null),this.cubeCamera&&(this.cubeCamera.destroy(),this.cubeCamera=null),this.cubeEntity&&(this.cubeEntity.destroy(),this.cubeEntity=null),this.cubeMaterial&&(this.cubeMaterial.destroy(),this.cubeMaterial=null),this.cubeRoot&&(this.cubeRoot.destroy(),this.cubeRoot=null),this.cubeLayer){const t=this.app.scene.layers,e=t.getLayerById(this.cubeLayer.id);e&&t.remove(e),this.cubeLayer=null}this.useParentDiv&&this.separateCanvas&&(this.separateCanvas.parentElement&&this.separateCanvas.parentElement.removeChild(this.separateCanvas),this.separateCanvas=null,this.parentDiv=null),this.app=this.mainApp,this.initialized=!1}destroy(){if(this.initialized)try{this.cleanup()}catch(t){this.initialized=!1}}isInitialized(){return this.initialized}getMinimumCanvasSize(){return this.useParentDiv?this.MIN_PARENT_DIV_SIZE:this.MIN_CANVAS_SIZE}isVisibleOnCanvas(){return this.visible&&this.initialized&&this.shouldShowCube()}getCanvasDimensions(){const t=this.app.graphicsDevice.canvas;return t?{width:t.width,height:t.height}:null}getViewport(){if(!this.cubeCamera||!this.cubeCamera.camera)return null;if(this.useParentDiv)return{x:0,y:0,width:1,height:1};const t=this.cubeCamera.camera.rect;return{x:t.x,y:t.y,width:t.z,height:t.w}}getCanvas(){return this.useParentDiv&&this.separateCanvas?this.separateCanvas:this.app.graphicsDevice.canvas}getParentDiv(){return this.parentDiv}isUsingParentDiv(){return this.useParentDiv}}const wz={enableStats:!1,autoFocus:!0,maxSplats:2e6,previewMode:!1,camera:{position:{x:0,y:0,z:10},target:{x:0,y:0,z:0},distance:10,minDistance:.1,maxDistance:1e5,orbitSensitivity:.3,panSensitivity:1,zoomSensitivity:.1},navigationCube:{enabled:!1,cubeSize:150,position:{x:0,y:0},padding:{x:50,y:100},transitionDuration:600,controlPointRadius:6,controlPointColor:{normal:"#ffffff",hover:"#FB7347"},continuousRotationSpeed:45}};function Az(t){if(!t)return null;try{return JSON.parse(t)}catch(t){return null}}function Cz(t){return"boolean"==typeof t?t:"string"==typeof t&&(""===t||("true"===t.toLowerCase()||"1"===t))}function Mz(t,e=0){if("number"==typeof t)return t;if("string"==typeof t){const i=parseFloat(t);return isNaN(i)?e:i}return e}class Pz{constructor(t={}){this._app=null,this._mainCamera=null,this._orbitScript=null,this.emitEvent=null,this.initialized=!1,this.cubeRenderer=null,this.controlPointManager=null,this.transitionController=null;const e=wz.navigationCube;if(!e)throw new Error("NavigationCubeController: DEFAULT_CONFIG.navigationCube is not defined");this.config={...e,...t},this._enabled=this.config.enabled}get enabled(){return this._enabled}initialize(t,e,i,s){if(!this.initialized&&this._enabled&&t&&e&&i){this._app=t,this._mainCamera=e,this._orbitScript=i,this.emitEvent=s||null;try{this.cubeRenderer=new bz(t,this.config),this.cubeRenderer.initialize(),this.cubeRenderer.setResizeCallback(()=>{this.updateControlPointPositions()});const e=this.cubeRenderer.getCanvas()||t.graphicsDevice.canvas,s=this.cubeRenderer.getParentDiv();this.controlPointManager=new uD(this.config,e,this.onControlPointClick.bind(this),this.onControlPointPressStart.bind(this),this.onControlPointPressEnd.bind(this),s),this.controlPointManager.initialize(),this.updateControlPointPositions(),this.transitionController=new dD(i,this.config.transitionDuration),void 0!==this.config.continuousRotationSpeed&&this.transitionController.setContinuousRotationSpeed(this.config.continuousRotationSpeed),this.initialized=!0}catch(t){this.cleanup(),this.initialized=!1}}}update(t){if(this.initialized&&this._enabled&&!("number"!=typeof t||t<0)&&isFinite(t))try{this.cubeRenderer&&this.cubeRenderer.render(),this.transitionController&&this.transitionController.update(t)}catch(t){}}updateControlPointPositions(){if(!this.controlPointManager||!this.cubeRenderer)return;const t=this.cubeRenderer.getViewport();t?this.controlPointManager.updateControlPointPositions(t):this.controlPointManager.updateControlPointPositions()}onControlPointClick(t){if(this.initialized&&this._enabled)try{this.snapToView(t)}catch(t){}}onControlPointPressStart(t){if(this.initialized&&this._enabled)try{this.transitionController&&this.transitionController.startContinuousRotation(t),this.emitEvent&&this.emitEvent("navigation-cube:continuous-rotation-start",{direction:t})}catch(t){}}onControlPointPressEnd(t){if(this.initialized&&this._enabled)try{this.transitionController&&this.transitionController.stopContinuousRotation(),this.emitEvent&&this.emitEvent("navigation-cube:continuous-rotation-end",{direction:t})}catch(t){}}syncWithCamera(t,e){if(this.initialized&&this._enabled&&"number"==typeof t&&"number"==typeof e)try{this.cubeRenderer&&this.cubeRenderer.setRotation(t,e)}catch(t){}}async snapToView(t){if(!this.initialized||!this._enabled)return Promise.reject(new Error("NavigationCubeController not initialized or disabled"));if(![cD.TOP,cD.BOTTOM,cD.LEFT,cD.RIGHT].includes(t))return Promise.reject(new Error(`Invalid direction: ${t}`));try{if(this.transitionController?.isTransitionActive()&&this.transitionController.cancelTransition("interrupted"),this.controlPointManager){const e=this.controlPointManager.getControlPoint(t);if(e?.element){const t=e.element,i=t.style.transform;t.style.transition="transform 100ms ease-out",t.style.transform="scale(1.4)",setTimeout(()=>{t.style.transition="background-color 200ms ease-in-out, transform 200ms ease-in-out, box-shadow 200ms ease-in-out",t.style.transform=i},100)}}if(!this.transitionController)throw new Error("TransitionController not initialized");const e=this.transitionController.calculateTargetState(t);if(!this.transitionController.validateTargetState(e))throw new Error("Invalid target state calculated");this.emitEvent&&this.emitEvent("navigation-cube:view-change-start",{direction:t});try{await this.transitionController.startTransition(e),this.emitEvent&&this.emitEvent("navigation-cube:view-change-complete",{direction:t})}catch(e){throw this.emitEvent&&this.emitEvent("navigation-cube:view-change-cancel",{direction:t,reason:e.message||"unknown"}),e}}catch(e){return this.emitEvent&&this.emitEvent("navigation-cube:view-change-cancel",{direction:t,reason:e instanceof Error?e.message:"unknown error"}),Promise.reject(e)}}setEnabled(t){if(this._enabled!==t&&(this._enabled=t,this.initialized))try{t?(this.cubeRenderer?.setVisible(!0),this.controlPointManager?.setVisible(!0)):(this.cubeRenderer?.setVisible(!1),this.controlPointManager?.setVisible(!1),this.transitionController?.cancelTransition("disabled"))}catch(t){}}updateConfig(t){const e=this.validateConfig(t);if(this.config={...this.config,...e},this.initialized)try{void 0!==e.cubeSize&&this.cubeRenderer&&(this.cubeRenderer.updateSize(e.cubeSize),this.updateControlPointPositions()),void 0!==e.controlPointColor&&this.controlPointManager&&this.controlPointManager.updateColors(e.controlPointColor),void 0!==e.controlPointRadius&&this.controlPointManager&&this.controlPointManager.updateRadius(e.controlPointRadius),void 0===e.padding&&void 0===e.position&&void 0===e.cubeSize||!this.controlPointManager||this.updateControlPointPositions(),void 0!==e.transitionDuration&&this.transitionController&&this.transitionController.setDuration(e.transitionDuration),void 0!==e.continuousRotationSpeed&&this.transitionController&&this.transitionController.setContinuousRotationSpeed(e.continuousRotationSpeed)}catch(t){}}validateConfig(t){const e={};if(void 0!==t.cubeSize&&"number"==typeof t.cubeSize&&isFinite(t.cubeSize)&&(e.cubeSize=Math.max(50,Math.min(500,t.cubeSize)),e.cubeSize,t.cubeSize),void 0!==t.controlPointRadius&&"number"==typeof t.controlPointRadius&&isFinite(t.controlPointRadius)&&(e.controlPointRadius=Math.max(4,Math.min(20,t.controlPointRadius)),e.controlPointRadius,t.controlPointRadius),void 0!==t.transitionDuration&&"number"==typeof t.transitionDuration&&isFinite(t.transitionDuration)&&(e.transitionDuration=Math.max(100,Math.min(3e3,t.transitionDuration)),e.transitionDuration,t.transitionDuration),void 0!==t.padding&&"object"==typeof t.padding&&null!==t.padding&&"number"==typeof t.padding.x&&"number"==typeof t.padding.y){const i=Math.max(0,Math.min(500,t.padding.x)),s=Math.max(0,Math.min(500,t.padding.y));e.padding={x:i,y:s},i!==t.padding.x||t.padding.y}if(void 0!==t.position&&"object"==typeof t.position&&null!==t.position&&"number"==typeof t.position.x&&"number"==typeof t.position.y){const i=Math.max(0,Math.min(1,t.position.x)),s=Math.max(0,Math.min(1,t.position.y));e.position={x:i,y:s},i!==t.position.x||t.position.y}return void 0!==t.controlPointColor&&"object"==typeof t.controlPointColor&&null!==t.controlPointColor&&"string"==typeof t.controlPointColor.normal&&"string"==typeof t.controlPointColor.hover&&this.isValidColor(t.controlPointColor.normal)&&this.isValidColor(t.controlPointColor.hover)&&(e.controlPointColor={normal:t.controlPointColor.normal,hover:t.controlPointColor.hover}),void 0!==t.enabled&&"boolean"==typeof t.enabled&&(e.enabled=t.enabled),void 0!==t.continuousRotationSpeed&&"number"==typeof t.continuousRotationSpeed&&isFinite(t.continuousRotationSpeed)&&(e.continuousRotationSpeed=Math.max(10,Math.min(180,t.continuousRotationSpeed)),e.continuousRotationSpeed,t.continuousRotationSpeed),e}isValidColor(t){if(/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(t))return!0;if(/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/i.test(t))return!0;if(/^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*[\d.]+\s*)?\)$/i.test(t))return!0;return!!["white","black","red","green","blue","yellow","orange","purple","pink","gray","grey","transparent"].includes(t.toLowerCase())}cancelTransition(t="manual-interaction"){if(this.initialized)try{this.transitionController&&this.transitionController.cancelTransition(t)}catch(t){}}onCanvasResize(){if(this.initialized&&this._enabled)try{this.cubeRenderer&&this.cubeRenderer.onCanvasResize(),this.controlPointManager&&this.updateControlPointPositions()}catch(t){}}cleanup(){this.transitionController&&(this.transitionController.cancelTransition("cleanup"),this.transitionController=null),this.controlPointManager&&(this.controlPointManager.destroy(),this.controlPointManager=null),this.cubeRenderer&&(this.cubeRenderer.destroy(),this.cubeRenderer=null),this._app=null,this._mainCamera=null,this._orbitScript=null}destroy(){if(this.initialized)try{this.cleanup(),this.initialized=!1}catch(t){this.initialized=!1}}getConfig(){return{...this.config}}isInitialized(){return this.initialized}}function Rz(t){return"number"==typeof t&&Number.isFinite(t)}function Lz(t,e){if(null==t)return e.clone();const i=t;if("function"==typeof i.clone&&Rz(i.x)&&Rz(i.y)&&Rz(i.z))return i;if(Array.isArray(t)){const[i,s,n]=t;return Rz(i)&&Rz(s)&&Rz(n)?new K(i,s,n):e.clone()}return Rz(i.x)&&Rz(i.y)&&Rz(i.z)?new K(i.x,i.y,i.z):Rz(i.r)&&Rz(i.g)&&Rz(i.b)?new K(i.r,i.g,i.b):e.clone()}const Dz=new WeakMap;function Iz(t){const e=Dz.get(t);if(e)return e;const i=function(t){const e=new Gi(t,{width:32,height:32,format:7,mipmaps:!1});e.addressU=0,e.addressV=0,e.minFilter=0,e.magFilter=0;const i=e.lock();let s=1337;const n=()=>(s^=s<<13,s^=s>>>17,s^=s<<5,(s>>>0)%256/255);for(let t=0;t<1024;t++){const e=Math.floor(255*n()),s=4*t;i[s+0]=e,i[s+1]=e,i[s+2]=e,i[s+3]=255}return e.unlock(),e.name="supersplat-blue-noise",e}(t);return Dz.set(t,i),i}const Oz=new K;class Nz{constructor(){this.boxes=new Map,this.nextId=0,this.app=null,this.parent=null,this.camera=null,this.onEvent=null,this.interactionEnabled=!0,this.selectedBoxId=null,this.cameraControlCallback=null,this.gizmoLayer=null,this.translateGizmo=null,this.attachedBoxId=null}initialize(t,e,i,s){this.app=t,this.parent=e,this.camera=i,this.onEvent=s||null,this.ensureTranslateGizmo()}setInteractionEnabled(t){this.interactionEnabled=t,this.updateGizmoAttachment()}setCameraControlCallback(t){this.cameraControlCallback=t}update(){this.ensureTranslateGizmo(),this.updateGizmoSize(),this.updateGizmoAttachment(),this.updateBoxShaderUniforms()}createBox(t={}){if(!this.app||!this.parent)return this.emitError(null,"BoxSelectionAPI not initialized","NOT_INITIALIZED"),null;const e="box_"+this.nextId++,i=t.sizeX??2,s=t.sizeY??2,n=t.sizeZ??2,r=Lz(t.color,new K(1,1,1)),a=t.visible??!0,o=new z_(e);o.addComponent("render",{type:"box",material:this.buildWireframeMaterial(r)}),o.setLocalScale(i,s,n),o.setLocalPosition(t.positionX??0,t.positionY??0,t.positionZ??0),o.render.castShadows=!1,o.render.receiveShadows=!1,o.render.enabled=a,this.parent.addChild(o);const l={id:e,entity:o,lenX:i,lenY:s,lenZ:n,color:r.clone(),visible:a};return this.boxes.set(e,l),this.selectedBoxId=e,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-created",{id:e}),e}removeBox(t){const e=this.boxes.get(t);if(!e)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1;if(e.entity.destroy(),this.boxes.delete(t),this.selectedBoxId===t){const t=this.boxes.keys().next().value;this.selectedBoxId=t??null}return this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-removed",{id:t}),!0}clear(){for(const t of Array.from(this.boxes.keys()))this.removeBox(t)}setBoxSize(t,e,i,s){const n=this.boxes.get(t);return n?e<=0||i<=0||s<=0?(this.emitError(t,"Box dimensions must be positive","INVALID_DIMENSIONS"),!1):(n.lenX=e,n.lenY=i,n.lenZ=s,n.entity.setLocalScale(e,i,s),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxSize(t){const e=this.boxes.get(t);return e?{x:e.lenX,y:e.lenY,z:e.lenZ}:null}setBoxPosition(t,e,i,s){const n=this.boxes.get(t);return n?(n.entity.setLocalPosition(e,i,s),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxPosition(t){const e=this.boxes.get(t);return e?e.entity.getLocalPosition().clone():null}setBoxColor(t,e,i,s){const n=this.boxes.get(t);if(!n)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1;n.color.set(e,i,s);const r=n.entity.render?.material;return r?.setParameter?.("lineColor",[n.color.x,n.color.y,n.color.z]),this.requestRender(),!0}getBoxColor(t){const e=this.boxes.get(t);return e?e.color.clone():null}showBox(t,e){const i=this.boxes.get(t);return i?(i.visible=e,i.entity.render.enabled=e,this.updateGizmoAttachment(),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}getBoxProperties(t){const e=this.boxes.get(t);return e?{id:t,size:{x:e.lenX,y:e.lenY,z:e.lenZ},position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()}:null}getAllBoxes(){const t=[];return this.boxes.forEach((e,i)=>{t.push({id:i,size:{x:e.lenX,y:e.lenY,z:e.lenZ},position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()})}),t}getSelectedBoxId(){return this.selectedBoxId}selectBox(t){return null===t?(this.selectedBoxId=null,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-selected",{id:null}),!0):this.boxes.has(t)?(this.selectedBoxId=t,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("box-selected",{id:t}),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}resetBox(t){const e=this.boxes.get(t);return e?(e.lenX=2,e.lenY=2,e.lenZ=2,e.entity.setLocalScale(2,2,2),e.entity.setLocalPosition(0,0,0),this.requestRender(),!0):(this.emitError(t,"Box not found","BOX_NOT_FOUND"),!1)}duplicateBox(t){const e=this.boxes.get(t);if(!e)return this.emitError(t,"Box not found","BOX_NOT_FOUND"),null;const i=e.entity.getLocalPosition();return this.createBox({sizeX:e.lenX,sizeY:e.lenY,sizeZ:e.lenZ,positionX:i.x+1,positionY:i.y,positionZ:i.z,color:e.color.clone(),visible:e.visible})}getBoxAtPosition(t){return null}setInteractionEnabledForBox(t,e){}requestRender(){const t=this.app;t&&(t.renderNextFrame=!0)}ensureTranslateGizmo(){if(this.app&&this.camera&&this.camera.camera){if(!this.gizmoLayer){this.gizmoLayer=this.app.scene.layers.getLayerByName("Gizmo"),this.gizmoLayer||(this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0}),this.app.scene.layers.push(this.gizmoLayer));const t=this.camera.camera;t&&Array.isArray(t.layers)&&!t.layers.includes(this.gizmoLayer.id)&&(t.layers=t.layers.concat([this.gizmoLayer.id]))}if(!this.translateGizmo){const t=this.camera.camera;this.translateGizmo=new bL(t,this.gizmoLayer),this.translateGizmo.enabled=!0,this.translateGizmo.on("render:update",()=>{this.requestRender()}),this.translateGizmo.on("transform:start",()=>{this.cameraControlCallback?.(!1),this.requestRender()}),this.translateGizmo.on("transform:move",()=>{const t=this.selectedBoxId;t&&this.boxes.has(t)&&this.emitEvent("box-moved",{id:t,position:this.boxes.get(t).entity.getLocalPosition().clone()}),this.requestRender()}),this.translateGizmo.on("transform:end",()=>{this.cameraControlCallback?.(!0),this.requestRender()}),this.updateGizmoSize()}}}updateGizmoSize(){if(!(this.translateGizmo&&this.app&&this.camera&&this.camera.camera))return;const t=this.app.graphicsDevice.canvas,e=1===this.camera.camera.projection;this.translateGizmo.size=e?1125/Math.max(1,t.clientHeight):1200/Math.max(1,Math.max(t.clientWidth,t.clientHeight))}updateGizmoAttachment(){if(!this.translateGizmo)return;const t=this.interactionEnabled&&!!this.selectedBoxId,e=this.selectedBoxId?this.boxes.get(this.selectedBoxId):void 0;t&&e&&e.visible?this.attachedBoxId!==e.id&&(this.translateGizmo.attach([e.entity]),this.attachedBoxId=e.id,this.requestRender()):null!==this.attachedBoxId&&(this.translateGizmo.detach(),this.attachedBoxId=null,this.requestRender())}buildWireframeMaterial(t){const e=new Sp({uniqueName:"boxSelectionSupersplatWire",vertexGLSL:"\n attribute vec3 vertex_position;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n void main() {\n gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);\n }\n",fragmentGLSL:'\n // ray-box intersection in box space\n bool intersectBox(out float t0, out float t1, out int axis0, out int axis1, vec3 pos, vec3 dir, vec3 boxCen, vec3 boxLen)\n {\n bvec3 validDir = notEqual(dir, vec3(0.0));\n vec3 absDir = abs(dir);\n vec3 signDir = sign(dir);\n vec3 m = vec3(\n validDir.x ? 1.0 / absDir.x : 0.0,\n validDir.y ? 1.0 / absDir.y : 0.0,\n validDir.z ? 1.0 / absDir.z : 0.0\n ) * signDir;\n\n vec3 n = m * (pos - boxCen);\n vec3 k = abs(m) * boxLen;\n\n vec3 v0 = -n - k;\n vec3 v1 = -n + k;\n\n // replace invalid axes with -inf and +inf so the tests below ignore them\n v0 = mix(vec3(-1.0 / 0.0000001), v0, validDir);\n v1 = mix(vec3(1.0 / 0.0000001), v1, validDir);\n\n axis0 = (v0.x > v0.y) ? ((v0.x > v0.z) ? 0 : 2) : ((v0.y > v0.z) ? 1 : 2);\n axis1 = (v1.x < v1.y) ? ((v1.x < v1.z) ? 0 : 2) : ((v1.y < v1.z) ? 1 : 2);\n\n t0 = v0[axis0];\n t1 = v1[axis1];\n\n if (t0 > t1 || t1 < 0.0) {\n return false;\n }\n\n return true;\n }\n\n float calcDepth(in vec3 pos, in mat4 viewProjection) {\n vec4 v = viewProjection * vec4(pos, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n uniform sampler2D blueNoiseTex32;\n uniform mat4 matrix_viewProjection;\n uniform vec3 boxCen;\n uniform vec3 boxLen;\n\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n uniform vec2 targetSize;\n uniform vec3 lineColor;\n\n bool writeDepth(float alpha) {\n ivec2 uv = ivec2(gl_FragCoord.xy);\n ivec2 size = textureSize(blueNoiseTex32, 0);\n return alpha > texelFetch(blueNoiseTex32, uv % size, 0).y;\n }\n\n bool strips(vec3 pos, int axis) {\n // Thickness tuned to match SuperSplat viewer "thick wire"\n bvec3 b = lessThan(fract(pos * 2.0 + vec3(0.015)), vec3(0.06));\n b[axis] = false;\n return any(b);\n }\n\n void main() {\n vec2 clip = gl_FragCoord.xy / targetSize;\n vec3 worldNear = near_origin + near_x * clip.x + near_y * clip.y;\n vec3 worldFar = far_origin + far_x * clip.x + far_y * clip.y;\n vec3 rayDir = normalize(worldFar - worldNear);\n\n float t0, t1;\n int axis0, axis1;\n if (!intersectBox(t0, t1, axis0, axis1, worldNear, rayDir, boxCen, boxLen)) {\n discard;\n }\n\n vec3 frontPos = worldNear + rayDir * t0;\n bool front = t0 > 0.0 && strips(frontPos - boxCen, axis0);\n\n vec3 backPos = worldNear + rayDir * t1;\n bool back = strips(backPos - boxCen, axis1);\n\n if (front) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(frontPos, matrix_viewProjection) : 1.0;\n } else if (back) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(backPos, matrix_viewProjection) : 1.0;\n } else {\n discard;\n }\n }\n'});return e.cull=2,e.blendState=new Ji(!0,0,6,8,0,1,8),e.update(),e.setParameter("lineColor",[t.x,t.y,t.z]),e}updateBoxShaderUniforms(){if(!this.app)return;const t=this.app.graphicsDevice;t.scope.resolve("targetSize").setValue([t.width,t.height]),t.scope.resolve("blueNoiseTex32").setValue(Iz(t));for(const t of this.boxes.values()){const e=t.entity.render?.material;e?.setParameter&&(t.entity.getWorldTransform().getTranslation(Oz),e.setParameter("boxCen",[Oz.x,Oz.y,Oz.z]),e.setParameter("boxLen",[.5*t.lenX,.5*t.lenY,.5*t.lenZ]))}}emitEvent(t,e){this.onEvent&&this.onEvent(t,e)}emitError(t,e,i){this.emitEvent("box-selection-error",{boxId:t,message:e,code:i})}}const Fz=new K;class Uz{constructor(){this.spheres=new Map,this.nextId=0,this.app=null,this.parent=null,this.camera=null,this.onEvent=null,this.interactionEnabled=!0,this.selectedSphereId=null,this.cameraControlCallback=null,this.gizmoLayer=null,this.translateGizmo=null,this.attachedSphereId=null}initialize(t,e,i,s){this.app=t,this.parent=e,this.camera=i,this.onEvent=s||null,this.ensureTranslateGizmo()}setInteractionEnabled(t){this.interactionEnabled=t,this.updateGizmoAttachment()}setCameraControlCallback(t){this.cameraControlCallback=t}update(){this.ensureTranslateGizmo(),this.updateGizmoSize(),this.updateGizmoAttachment(),this.updateSphereShaderUniforms()}createSphere(t={}){if(!this.app||!this.parent)return this.emitError(null,"SphereSelectionAPI not initialized","NOT_INITIALIZED"),null;const e="sphere_"+this.nextId++,i=t.radius??1,s=Lz(t.color,new K(1,1,1)),n=t.visible??!0,r=new z_(e);r.addComponent("render",{type:"box",material:this.buildWireframeMaterial(s)}),r.setLocalScale(2*i,2*i,2*i),r.setLocalPosition(t.positionX??0,t.positionY??0,t.positionZ??0),r.render.castShadows=!1,r.render.receiveShadows=!1,r.render.enabled=n,this.parent.addChild(r);const a={id:e,entity:r,radius:i,color:s.clone(),visible:n};return this.spheres.set(e,a),this.selectedSphereId=e,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-created",{id:e}),e}removeSphere(t){const e=this.spheres.get(t);if(!e)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1;if(e.entity.destroy(),this.spheres.delete(t),this.selectedSphereId===t){const t=this.spheres.keys().next().value;this.selectedSphereId=t??null}return this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-removed",{id:t}),!0}clear(){for(const t of Array.from(this.spheres.keys()))this.removeSphere(t)}setSphereRadius(t,e){const i=this.spheres.get(t);return i?e<=0?(this.emitError(t,"Sphere radius must be positive","INVALID_RADIUS"),!1):(i.radius=e,i.entity.setLocalScale(2*e,2*e,2*e),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSphereRadius(t){const e=this.spheres.get(t);return e?e.radius:null}setSpherePosition(t,e,i,s){const n=this.spheres.get(t);return n?(n.entity.setLocalPosition(e,i,s),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSpherePosition(t){const e=this.spheres.get(t);return e?e.entity.getLocalPosition().clone():null}setSphereColor(t,e,i,s){const n=this.spheres.get(t);if(!n)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1;n.color.set(e,i,s);const r=n.entity.render?.material;return r?.setParameter?.("lineColor",[n.color.x,n.color.y,n.color.z]),this.requestRender(),!0}getSphereColor(t){const e=this.spheres.get(t);return e?e.color.clone():null}showSphere(t,e){const i=this.spheres.get(t);return i?(i.visible=e,i.entity.render.enabled=e,this.updateGizmoAttachment(),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}getSphereProperties(t){const e=this.spheres.get(t);return e?{id:t,radius:e.radius,position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()}:null}getAllSpheres(){const t=[];return this.spheres.forEach((e,i)=>{t.push({id:i,radius:e.radius,position:e.entity.getLocalPosition().clone(),visible:e.visible,color:e.color.clone()})}),t}getSelectedSphereId(){return this.selectedSphereId}selectSphere(t){return null===t?(this.selectedSphereId=null,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-selected",{id:null}),!0):this.spheres.has(t)?(this.selectedSphereId=t,this.updateGizmoAttachment(),this.requestRender(),this.emitEvent("sphere-selected",{id:t}),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}resetSphere(t){const e=this.spheres.get(t);return e?(e.radius=1,e.entity.setLocalScale(2,2,2),e.entity.setLocalPosition(0,0,0),this.requestRender(),!0):(this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),!1)}duplicateSphere(t){const e=this.spheres.get(t);if(!e)return this.emitError(t,"Sphere not found","SPHERE_NOT_FOUND"),null;const i=e.entity.getLocalPosition();return this.createSphere({radius:e.radius,positionX:i.x+1,positionY:i.y,positionZ:i.z,color:e.color.clone(),visible:e.visible})}getSphereAtPosition(t){return null}setInteractionEnabledForSphere(t,e){}requestRender(){const t=this.app;t&&(t.renderNextFrame=!0)}ensureTranslateGizmo(){if(this.app&&this.camera&&this.camera.camera){if(!this.gizmoLayer){this.gizmoLayer=this.app.scene.layers.getLayerByName("Gizmo"),this.gizmoLayer||(this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0}),this.app.scene.layers.push(this.gizmoLayer));const t=this.camera.camera;t&&Array.isArray(t.layers)&&!t.layers.includes(this.gizmoLayer.id)&&(t.layers=t.layers.concat([this.gizmoLayer.id]))}if(!this.translateGizmo){const t=this.camera.camera;this.translateGizmo=new bL(t,this.gizmoLayer),this.translateGizmo.enabled=!0,this.translateGizmo.on("render:update",()=>{this.requestRender()}),this.translateGizmo.on("transform:start",()=>{this.cameraControlCallback?.(!1),this.requestRender()}),this.translateGizmo.on("transform:move",()=>{const t=this.selectedSphereId;t&&this.spheres.has(t)&&this.emitEvent("sphere-moved",{id:t,position:this.spheres.get(t).entity.getLocalPosition().clone()}),this.requestRender()}),this.translateGizmo.on("transform:end",()=>{this.cameraControlCallback?.(!0),this.requestRender()}),this.updateGizmoSize()}}}updateGizmoSize(){if(!(this.translateGizmo&&this.app&&this.camera&&this.camera.camera))return;const t=this.app.graphicsDevice.canvas,e=1===this.camera.camera.projection;this.translateGizmo.size=e?1125/Math.max(1,t.clientHeight):1200/Math.max(1,Math.max(t.clientWidth,t.clientHeight))}updateGizmoAttachment(){if(!this.translateGizmo)return;const t=this.interactionEnabled&&!!this.selectedSphereId,e=this.selectedSphereId?this.spheres.get(this.selectedSphereId):void 0;t&&e&&e.visible?this.attachedSphereId!==e.id&&(this.translateGizmo.attach([e.entity]),this.attachedSphereId=e.id,this.requestRender()):null!==this.attachedSphereId&&(this.translateGizmo.detach(),this.attachedSphereId=null,this.requestRender())}buildWireframeMaterial(t){const e=new Sp({uniqueName:"sphereSelectionSupersplatWire",vertexGLSL:"\n attribute vec3 vertex_position;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n void main() {\n gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);\n }\n",fragmentGLSL:'\n bool intersectSphere(out float t0, out float t1, vec3 pos, vec3 dir, vec4 sphere) {\n vec3 L = sphere.xyz - pos;\n float tca = dot(L, dir);\n\n float d2 = sphere.w * sphere.w - (dot(L, L) - tca * tca);\n if (d2 <= 0.0) {\n return false;\n }\n\n float thc = sqrt(d2);\n t0 = tca - thc;\n t1 = tca + thc;\n if (t1 <= 0.0) {\n return false;\n }\n\n return true;\n }\n\n float calcDepth(in vec3 pos, in mat4 viewProjection) {\n vec4 v = viewProjection * vec4(pos, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n vec2 calcAzimuthElev(in vec3 dir) {\n float azimuth = atan(dir.z, dir.x);\n float elev = asin(dir.y);\n return vec2(azimuth, elev) * 180.0 / 3.14159;\n }\n\n uniform sampler2D blueNoiseTex32;\n uniform mat4 matrix_viewProjection;\n uniform vec4 sphere;\n uniform vec3 lineColor;\n\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n uniform vec2 targetSize;\n\n bool writeDepth(float alpha) {\n vec2 uv = fract(gl_FragCoord.xy / 32.0);\n float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;\n return alpha > noise;\n }\n\n bool strips(vec3 lp) {\n vec2 ae = calcAzimuthElev(normalize(lp));\n\n float spacing = 180.0 / (2.0 * 3.14159 * sphere.w);\n // Thickness tuned to match SuperSplat viewer "thick wire"\n float size = 0.06;\n return fract(ae.x / spacing) < size ||\n fract(ae.y / spacing) < size;\n }\n\n void main() {\n vec2 clip = gl_FragCoord.xy / targetSize;\n vec3 worldNear = near_origin + near_x * clip.x + near_y * clip.y;\n vec3 worldFar = far_origin + far_x * clip.x + far_y * clip.y;\n\n vec3 rayDir = normalize(worldFar - worldNear);\n\n float t0, t1;\n if (!intersectSphere(t0, t1, worldNear, rayDir, sphere)) {\n discard;\n }\n\n vec3 frontPos = worldNear + rayDir * t0;\n bool front = t0 > 0.0 && strips(frontPos - sphere.xyz);\n\n vec3 backPos = worldNear + rayDir * t1;\n bool back = strips(backPos - sphere.xyz);\n\n if (front) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(frontPos, matrix_viewProjection) : 1.0;\n } else if (back) {\n gl_FragColor = vec4(lineColor, 0.6);\n gl_FragDepth = writeDepth(0.6) ? calcDepth(backPos, matrix_viewProjection) : 1.0;\n } else {\n discard;\n }\n }\n'});return e.cull=2,e.blendState=new Ji(!0,0,6,8,0,1,8),e.update(),e.setParameter("lineColor",[t.x,t.y,t.z]),e}updateSphereShaderUniforms(){if(!this.app)return;const t=this.app.graphicsDevice;t.scope.resolve("targetSize").setValue([t.width,t.height]),t.scope.resolve("blueNoiseTex32").setValue(Iz(t));for(const t of this.spheres.values()){const e=t.entity.render?.material;e?.setParameter&&(t.entity.getWorldTransform().getTranslation(Fz),e.setParameter("sphere",[Fz.x,Fz.y,Fz.z,t.radius]))}}emitEvent(t,e){this.onEvent&&this.onEvent(t,e)}emitError(t,e,i){this.emitEvent("sphere-selection-error",{sphereId:t,message:e,code:i})}}let Bz=0;class zz{constructor(t,e){this.readBytes=0,this.totalBytes=t,this.pull=async t=>{const i=await e(t);return this.readBytes+=i,i}}}const kz=(t,e)=>{const i=[];let s=0;const n=e.getReader();return new zz(t,async t=>{for(;s<t.byteLength;){const{done:t,value:e}=await n.read();if(t)break;i.push(e),s+=e.byteLength}let e=0;for(;e<t.byteLength&&i.length>0;){const n=i[0],r=Math.min(n.byteLength,t.byteLength-e);t.set(n.subarray(0,r),e),e+=r,s-=r,r<n.byteLength?i[0]=n.subarray(r):i.shift()}return e})};class Vz{constructor(t){this.source=t}async getReadStream(){const{source:t}=this;if(t instanceof ArrayBuffer)return kz(t.byteLength,(t=>{let e=0;return new ReadableStream({pull(i){if(e<t.byteLength){const s=Math.min(e+65536,t.byteLength),n=new Uint8Array(t,e,s-e);i.enqueue(n),e=s}else i.close()}})})(t));if(t instanceof Blob)return kz(t.size,t.stream());const e=t instanceof Response?t:await fetch(t instanceof Request?t:new Request(t));if(!e.ok)throw new Error(`Failed to fetch asset: ${e.status} ${e.statusText}`);if(!e.body)throw new Error("Response has no body");const i=e.headers.get("Content-Length");return kz(i?parseInt(i,10):0,e.body)}async arrayBuffer(){const{source:t}=this;if(t instanceof ArrayBuffer)return t;if(t instanceof Blob)return await t.arrayBuffer();const e=t instanceof Response?t:await fetch(t instanceof Request?t:new Request(t));if(!e.ok)throw new Error(`Failed to fetch asset: ${e.status} ${e.statusText}`);return await e.arrayBuffer()}}const Hz=async(t,e,i)=>{let s;return s=void 0===e||void 0===i?t.contents??t.url??t.filename:t.contents?t.contents.slice(e,i):await fetch(t.url??t.filename,{headers:{Range:`bytes=${e}-${i-1}`}}),new Vz(s)},Gz=1.414213562373095,Wz=.7071067811865475,Xz=t=>(t-.5)/.28209479177387814,Yz=t=>Math.log(t),qz=(t,e,i)=>(1-i)*t+i*e,jz=["x","y","z","nx","ny","nz","opacity","rot_0","rot_1","rot_2","rot_3","f_dc_0","f_dc_1","f_dc_2","scale_0","scale_1","scale_2"],$z=t=>new Float32Array(t),Kz=t=>{const e={};for(const i of jz)e[`property_${i}`]=$z(t);return e},Zz=(t,e,i,s,n,r,a)=>{const o=32*i;n.property_x[i]=t.getFloat32(o+0,!0),n.property_y[i]=t.getFloat32(o+4,!0),n.property_z[i]=t.getFloat32(o+8,!0),n.property_f_dc_0[i]=Xz(t.getUint8(o+12)/255),n.property_f_dc_1[i]=Xz(t.getUint8(o+13)/255),n.property_f_dc_2[i]=Xz(t.getUint8(o+14)/255),n.property_opacity[i]=(t=>-Math.log((1-t)/t))(t.getUint8(o+15)/255);const l=s.compressedScaleMin,h=s.compressedScaleMax;n.property_scale_0[i]=Yz(qz(l.x,h.x,t.getUint16(o+16,!0)/65535)),n.property_scale_1[i]=Yz(qz(l.y,h.y,t.getUint16(o+18,!0)/65535)),n.property_scale_2[i]=Yz(qz(l.z,h.z,t.getUint16(o+20,!0)/65535));const c=(t=>{const e=t>>30&3,i=(1023&t)/1023*Gz-Wz,s=(t>>10&1023)/1023*Gz-Wz,n=(t>>20&1023)/1023*Gz-Wz;let r=i*i+s*s+n*n;r=Math.min(1,r);const a=Math.sqrt(1-r);return 0===e?[a,i,s,n]:1===e?[i,a,s,n]:2===e?[i,s,a,n]:[i,s,n,a]})(t.getUint32(o+22,!0));if(n.property_rot_0[i]=c[3],n.property_rot_1[i]=c[0],n.property_rot_2[i]=c[1],n.property_rot_3[i]=c[2],n.property_nx[i]=t.getUint16(o+26,!0),n.property_ny[i]=t.getUint16(o+28,!0),n.property_nz[i]=t.getUint16(o+30,!0),a&&e&&r){const t=2*o,n=Array.from({length:15},(i,s)=>e.getUint32(t+4*s,!0)),{compressedSHMin:a,compressedSHMax:l}=s,h=n.map(t=>{return((t,e,i)=>new K(qz(t.x,e.x,i.x),qz(t.y,e.y,i.y),qz(t.z,e.z,i.z)))(a,l,new K((2047&(e=t))/2047,(e>>11&1023)/1023,(e>>21&2047)/2047));var e});for(let t=0;t<15;t++)r[t][i]=h[t].x,r[t+15][i]=h[t].y,r[t+30][i]=h[t].z}},Qz=async t=>{const{info:e,targetLod:i,isHasSH:s,dataFile:n,shFile:r,compressInfo:a,propertyOffset:o,properties:l,properties_f_rest:h}=t,c=e.lods[i],d=c.points,u=Number(c.offset),p=c.size;if(0===d)return o;const f=await Hz(n,u,u+p),m=new DataView(await f.arrayBuffer());let _;if(s){const t=await Hz(r,2*u,2*u+2*p);_=new DataView(await t.arrayBuffer())}const g=Kz(d),v=s?Array.from({length:45},()=>new Float32Array(d)):null;for(let t=0;t<d;t++)Zz(m,_,t,a,g,v,s);for(const t of jz)l[`property_${t}`].set(g[`property_${t}`],o);if(s&&h&&v)for(let t=0;t<45;t++)h[t].set(v[t],o);return o+d},Jz=async t=>{const e=await Hz(t),i=(new TextDecoder).decode(await e.arrayBuffer()),s=JSON.parse(i),n="Quality"===s.fileType&&!!t.mapFile("shcoef.bin"),r=(t=>{const e={};t.attributes.forEach(t=>{e[t.name]=t});const i=e.scale.min,s=e.scale.max,n=e.shcoef.min,r=e.shcoef.max;return{compressedScaleMin:new K(i[0],i[1],i[2]),compressedScaleMax:new K(s[0],s[1],s[2]),compressedSHMin:new K(n[0],n[1],n[2]),compressedSHMax:new K(r[0],r[1],r[2])}})(s),a=s.splats;let o=a.findIndex(t=>t<2e7);o<0&&(o=a.length-1);const l=a[o],h=t.mapFile("index.bin");if(!h)throw new Error("Failed to fetch index.bin");const c=new Vz(h.contents??h.url??h.filename),d=await c.arrayBuffer(),u=t.mapFile("data.bin"),p=n&&t.mapFile("shcoef.bin"),f=((t,e)=>{let i=0;const s=new DataView(t),n=[];for(;!(i>s.byteLength-1);){const t=s.getInt16(i,!0);i+=2;const r=s.getInt16(i,!0);i+=2;const a=[];for(let t=0;t<e.totalLevel;t++){const t=s.getInt32(i,!0);i+=4;const e=s.getBigInt64(i,!0);i+=8;const n=s.getInt32(i,!0);i+=4,a.push({points:t,offset:e,size:n})}const o={x:t,y:r,lods:a};n.push(o)}return n})(d,s);return await(async t=>{const{totalSplats:e,unitInfos:i,targetLod:s,isHasSH:n,dataFile:r,shFile:a,compressInfo:o}=t,l=Kz(e),h=n?Array.from({length:45},()=>$z(e)):null;let c=0;for(const t of i)c=await Qz({info:t,targetLod:s,isHasSH:n,dataFile:r,shFile:a,compressInfo:o,propertyOffset:c,properties:l,properties_f_rest:h});const d=new ym([{name:"vertex",count:e,properties:[...jz.map(t=>({type:"float",name:t,storage:l[`property_${t}`],byteSize:4})),...n&&h?h.map((t,e)=>({type:"float",name:`f_rest_${e}`,storage:t,byteSize:4})):[],{type:"float",name:"state",storage:new Uint8Array(e),byteSize:4}]}]);return d})({totalSplats:l,unitInfos:f,targetLod:o,isHasSH:n&&!!p,dataFile:u,shFile:p,compressInfo:r})},tk=async t=>{const e=await Hz(t);return(t=>{const e=t.byteLength/32,i=new DataView(t),s=new Float32Array(e),n=new Float32Array(e),r=new Float32Array(e),a=new Float32Array(e),o=new Float32Array(e),l=new Float32Array(e),h=new Float32Array(e),c=new Float32Array(e),d=new Float32Array(e),u=new Float32Array(e),p=new Float32Array(e),f=new Float32Array(e),m=new Float32Array(e),_=new Float32Array(e),g=new Uint8Array(e),v=.28209479177387814;let y;for(let t=0;t<e;t++)y=32*t,s[t]=i.getFloat32(y+0,!0),n[t]=i.getFloat32(y+4,!0),r[t]=i.getFloat32(y+8,!0),f[t]=Math.log(i.getFloat32(y+12,!0)),m[t]=Math.log(i.getFloat32(y+16,!0)),_[t]=Math.log(i.getFloat32(y+20,!0)),d[t]=(i.getUint8(y+24)/255-.5)/v,u[t]=(i.getUint8(y+25)/255-.5)/v,p[t]=(i.getUint8(y+26)/255-.5)/v,a[t]=-Math.log(255/i.getUint8(y+27)-1),o[t]=(i.getUint8(y+28)-128)/128,l[t]=(i.getUint8(y+29)-128)/128,h[t]=(i.getUint8(y+30)-128)/128,c[t]=(i.getUint8(y+31)-128)/128;return new ym([{name:"vertex",count:e,properties:[{type:"float",name:"x",storage:s,byteSize:4},{type:"float",name:"y",storage:n,byteSize:4},{type:"float",name:"z",storage:r,byteSize:4},{type:"float",name:"opacity",storage:a,byteSize:4},{type:"float",name:"rot_0",storage:o,byteSize:4},{type:"float",name:"rot_1",storage:l,byteSize:4},{type:"float",name:"rot_2",storage:h,byteSize:4},{type:"float",name:"rot_3",storage:c,byteSize:4},{type:"float",name:"f_dc_0",storage:d,byteSize:4},{type:"float",name:"f_dc_1",storage:u,byteSize:4},{type:"float",name:"f_dc_2",storage:p,byteSize:4},{type:"float",name:"scale_0",storage:f,byteSize:4},{type:"float",name:"scale_1",storage:m,byteSize:4},{type:"float",name:"scale_2",storage:_,byteSize:4},{type:"float",name:"state",storage:g,byteSize:4}]}])})(await e.arrayBuffer())};var ek;!function(t){t.camera="camera",t.model="model",t.splat="splat",t.shadow="shadow",t.debug="debug",t.other="other"}(ek||(ek={}));const ik=[ek.camera,ek.model,ek.splat,ek.shadow,ek.debug,ek.other];let sk=1,nk=class{constructor(t){this.scene=null,this.type=t,this.uid=sk++}destroy(){this.scene&&this.scene.remove(this)}add(){}remove(){}serialize(t){}onUpdate(t){}onPostUpdate(){}onPreRender(){}onPostRender(){}onAdded(t){}onRemoved(t){}move(t,e,i){}get worldBound(){return null}};var rk;!function(t){t[t.selected=1]="selected",t[t.locked=2]="locked",t[t.deleted=4]="deleted"}(rk||(rk={}));const ak=[0,4,8,12,1,5,9,13,2,6,10,14],ok=1536;class lk{constructor(t,e=4096){let i,s;const n=(e,n)=>{const r=new Gi(t,{name:"transformPalette",width:e,height:n,format:Nt,mipmaps:!1,addressU:1,addressV:1}),a=r.lock();r.unlock(),i&&(a.set(s),i.destroy()),i=r,s=a};this.getTransform=(t,e)=>{const i=e.data;for(let e=0;e<12;++e)i[ak[e]]=s[12*t+e]},this.setTransform=(t,e)=>{const n=e.data;for(let e=0;e<12;++e)s[12*t+e]=n[ak[e]];i.upload()};let r=1;this.alloc=(t=1)=>{const e=r;for(;r+t>s.length/12;)n(ok,2*i.height);return r+=t,e},this.free=(t=1)=>{r-=t},Object.defineProperty(this,"texture",{get:()=>i}),n(ok,Math.ceil(e/512)),this.setTransform(0,rt.IDENTITY)}}const hk=new K,ck=new K,dk=new K,uk=[-1,1].map(t=>[-1,1].map(e=>[-1,1].map(i=>[new K(t,e,i),new K(.75*t,e,i),new K(t,e,i),new K(t,.75*e,i),new K(t,e,i),new K(t,e,.75*i)]))).flat(3);class pk extends nk{constructor(t,e){super(ek.splat),this.numSplats=0,this.numDeleted=0,this.numLocked=0,this.numSelected=0,this.changedCounter=0,this.selectionBoundDirty=!0,this.localBoundDirty=!0,this.worldBoundDirty=!0,this._visible=!0,this.selectionAlpha=1,this._name="",this._tintClr=new H(1,1,1),this._temperature=0,this._saturation=1,this._brightness=0,this._blackPoint=0,this._whitePoint=1,this._transparency=1,this.measurePoints=[],this.measureSelection=-1;const i=t.resource,s=i.gsplatData,{device:n}=i;this._name=t.file.filename,this.asset=t,this.splatData=s,this.numSplats=s.numSplats,this.entity=new z_("splatEntitiy"),this.entity.setEulerAngles(e),this.entity.addComponent("gsplat",{asset:t});const r=this.entity.gsplat.instance;if(!r||!r.meshInstance)throw new Error("Failed to initialize gsplat component. The file may not contain valid Gaussian Splatting data.");r.meshInstance.calculateSortDistance=(t,e,i)=>{const s=this.localBound,n=this.entity.getWorldTransform();let r;for(let t=0;t<8;++t){hk.x=s.center.x+s.halfExtents.x*(1&t?1:-1),hk.y=s.center.y+s.halfExtents.y*(2&t?1:-1),hk.z=s.center.z+s.halfExtents.z*(4&t?1:-1),n.transformPoint(hk,hk);const a=hk.sub(e).dot(i);(0===t||a>r)&&(r=a)}return r},this.splatData.getProp("state")||this.splatData.getElement("vertex").properties.push({type:"uchar",name:"state",storage:new Uint8Array(this.splatData.numSplats),byteSize:1}),this.splatData.getElement("vertex").properties.push({type:"ushort",name:"transform",storage:new Uint16Array(this.splatData.numSplats),byteSize:2});const{width:a,height:o}=i.colorTexture,l=(t,e)=>new Gi(n,{name:t,width:a,height:o,format:e,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});this.stateTexture=l("splatState",Jt),this.transformTexture=l("splatTransform",qt),this.transformPalette=new lk(n),new Ji(!0,0,1,8),this.rebuildMaterial=t=>{const{material:e}=r,{glsl:i}=e.shaderChunks;i.set("gsplatVS",'\n#include "gsplatCommonVS"\n\nuniform sampler2D splatState;\n\nuniform vec4 selectedClr;\nuniform vec4 lockedClr;\n\nuniform vec3 clrOffset;\nuniform vec4 clrScale;\n\nvarying mediump vec3 texCoordIsLocked; // store locked flat in z\nvarying mediump vec4 color;\n\n#if PICK_PASS\n uniform uint pickMode; // 0: add, 1: remove, 2: set\n#endif\n\nmediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);\n\nuniform float saturation;\n\nvec3 applySaturation(vec3 color) {\n vec3 grey = vec3(dot(color, vec3(0.299, 0.587, 0.114)));\n return grey + (color - grey) * saturation;\n}\n\nvoid main(void) {\n // read gaussian details\n SplatSource source;\n if (!initSource(source)) {\n gl_Position = discardVec;\n return;\n }\n\n // get per-gaussian edit state, discard if deleted\n uint vertexState = uint(texelFetch(splatState, source.uv, 0).r * 255.0 + 0.5) & 7u;\n\n #if OUTLINE_PASS\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n #elif UNDERLAY_PASS\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n #elif PICK_PASS\n if (pickMode == 0u) {\n // add: skip deleted, locked and selected splats\n if (vertexState != 0u) {\n gl_Position = discardVec;\n return;\n }\n } else if (pickMode == 1u) {\n // remove: skip deleted, locked and unselected splats\n if (vertexState != 1u) {\n gl_Position = discardVec;\n return;\n }\n } else {\n // set: skip deleted and locked splats\n if ((vertexState & 6u) != 0u) {\n gl_Position = discardVec;\n return;\n }\n }\n #else\n if ((vertexState & 4u) != 0u) {\n gl_Position = discardVec;\n return;\n }\n #endif\n\n // get center\n vec3 modelCenter = readCenter(source);\n\n SplatCenter center;\n if (!initCenter(source, modelCenter, center)) {\n gl_Position = discardVec;\n return;\n }\n\n SplatCorner corner;\n if (!initCorner(source, center, corner)) {\n gl_Position = discardVec;\n return;\n }\n\n gl_Position = center.proj + vec4(corner.offset, 0.0, 0.0);\n\n // store texture coord and locked state\n texCoordIsLocked = vec3(corner.uv, (vertexState & 2u) != 0u ? 1.0 : 0.0);\n\n #if UNDERLAY_PASS\n color = readColor(source);\n color.xyz = mix(color.xyz, selectedClr.xyz * 0.2, selectedClr.a) * selectedClr.a;\n #elif PICK_PASS\n uvec4 bits = (uvec4(source.id) >> uvec4(0u, 8u, 16u, 24u)) & uvec4(255u);\n color = vec4(bits) / 255.0;\n // handle splat color\n #elif FORWARD_PASS\n // read color\n color = readColor(source);\n\n // evaluate spherical harmonics\n #if SH_BANDS > 0\n // calculate the model-space view direction\n vec3 dir = normalize(center.view * mat3(center.modelView));\n\n // read sh coefficients\n vec3 sh[SH_COEFFS];\n float scale;\n readSHData(source, sh, scale);\n\n // evaluate\n color.xyz += evalSH(sh, dir) * scale;\n #endif\n\n // apply tint/brightness\n color = color * clrScale + vec4(clrOffset, 0.0);\n\n // apply saturation\n color.xyz = applySaturation(color.xyz);\n\n // don\'t allow out-of-range alpha\n color.a = clamp(color.a, 0.0, 1.0);\n\n // apply tonemapping\n color = vec4(prepareOutputFromGamma(max(color.xyz, 0.0)), color.w);\n\n // apply locked/selected colors\n if ((vertexState & 2u) != 0u) {\n // locked\n color *= lockedClr;\n } else if ((vertexState & 1u) != 0u) {\n // selected\n color.xyz = mix(color.xyz, selectedClr.xyz * 0.8, selectedClr.a);\n }\n #endif\n}\n'),i.set("gsplatPS","\nvarying mediump vec3 texCoordIsLocked;\nvarying mediump vec4 color;\n\nuniform int mode; // 0: centers, 1: rings\nuniform float pickerAlpha;\nuniform float ringSize;\n\nconst float EXP4 = exp(-4.0);\nconst float INV_EXP4 = 1.0 / (1.0 - EXP4);\n\nfloat normExp(float x) {\n return (exp(x * -4.0) - EXP4) * INV_EXP4;\n}\n\nvoid main(void) {\n mediump float A = dot(texCoordIsLocked.xy, texCoordIsLocked.xy);\n\n if (A > 1.0) {\n discard;\n }\n\n #if OUTLINE_PASS\n gl_FragColor = vec4(1.0, 1.0, 1.0, mode == 0 ? exp(-A * 4.0) * color.a : 1.0);\n #else\n #ifdef PICK_PASS\n gl_FragColor = color;\n #else\n mediump float alpha = normExp(A) * color.a;\n\n if (texCoordIsLocked.z == 0.0 && ringSize > 0.0) {\n // rings mode\n if (A < 1.0 - ringSize) {\n alpha = max(0.05, alpha);\n } else {\n alpha = 0.6;\n }\n }\n\n gl_FragColor = vec4(color.xyz * alpha, alpha);\n #endif\n #endif\n}\n"),i.set("gsplatCenterVS","\nuniform mat4 matrix_model;\nuniform mat4 matrix_view;\nuniform mat4 matrix_projection;\n\nuniform highp usampler2D splatTransform; // per-splat index into transform palette\nuniform sampler2D transformPalette; // palette of transform matrices\n\nmat4 applyPaletteTransform(SplatSource source, mat4 model) {\n uint transformIndex = texelFetch(splatTransform, source.uv, 0).r;\n if (transformIndex == 0u) {\n return model;\n }\n\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n t[3] = vec4(0.0, 0.0, 0.0, 1.0);\n\n return model * transpose(t);\n}\n\n// project the model space gaussian center to view and clip space\nbool initCenter(SplatSource source, vec3 modelCenter, out SplatCenter center) {\n mat4 modelView = matrix_view * applyPaletteTransform(source, matrix_model);\n vec4 centerView = modelView * vec4(modelCenter, 1.0);\n\n // early out if splat is behind the camera\n if (centerView.z > 0.0) {\n return false;\n }\n\n vec4 centerProj = matrix_projection * centerView;\n\n // ensure gaussians are not clipped by camera near and far\n centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));\n\n center.view = centerView.xyz / centerView.w;\n center.proj = centerProj;\n center.projMat00 = matrix_projection[0][0];\n center.modelView = modelView;\n return true;\n}\n"),e.setDefine("SH_BANDS",`${Math.min(t,r.resource.shBands)}`),e.setParameter("splatState",this.stateTexture),e.setParameter("splatTransform",this.transformTexture),e.update()},this.selectionBoundStorage=new ut,this.localBoundStorage=r.resource.aabb,this.worldBoundStorage=r.meshInstance._aabb,r.meshInstance._updateAabb=!1,r.sorter.on("updated",()=>{this.changedCounter++})}destroy(){super.destroy(),this.entity.destroy(),this.asset.registry.remove(this.asset),this.asset.unload()}updateState(t=rk.selected){const e=this.splatData.getProp("state");this.stateTexture.lock().set(e),this.stateTexture.unlock();let i=0,s=0,n=0;for(let t=0;t<e.length;++t){const r=e[t];r&rk.deleted?n++:r&rk.locked?s++:r&rk.selected&&i++}this.numSplats=e.length-n,this.numLocked=s,this.numSelected=i,this.numDeleted=n,this.makeSelectionBoundDirty(),t&rk.deleted&&this.updateSorting(),this.scene.forceRender=!0,this.scene.events.fire("splat.stateChanged",this)}updatePositions(){const t=this.scene.dataProcessor.calcPositions(this),e=this.splatData.getProp("state"),{sorter:i}=this.entity.gsplat.instance,{centers:s}=i;for(let i=0;i<this.splatData.numSplats;++i)e[i]===rk.selected&&(s[3*i+0]=t[4*i],s[3*i+1]=t[4*i+1],s[3*i+2]=t[4*i+2]);this.updateSorting(),this.scene.forceRender=!0,this.scene.events.fire("splat.positionsChanged",this)}updateSorting(){const t=this.splatData.getProp("state");let e;if(this.makeLocalBoundDirty(),this.numSplats!==t.length){e=new Uint32Array(this.numSplats);let i=0;for(let s=0;s<t.length;++s)0===(t[s]&rk.deleted)&&(e[i++]=s)}this.entity.gsplat.instance.sorter.setMapping(e)}get worldTransform(){return this.entity.getWorldTransform()}set name(t){t!==this.name&&(this._name=t,this.scene.events.fire("splat.name",this))}get name(){return this._name}get filename(){return this.asset.file.filename}calcSplatWorldPosition(t,e){if(t>=this.splatData.numSplats)return!1;const{sorter:i}=this.entity.gsplat.instance,{centers:s}=i;return e.set(s[3*t+0],s[3*t+1],s[3*t+2]),this.worldTransform.transformPoint(e,e),!0}add(){this.scene.contentRoot.addChild(this.entity),this.scene.events.on("view.bands",this.rebuildMaterial,this),this.rebuildMaterial(this.scene.events.invoke("view.bands")),this.updateState()}remove(){this.scene.events.off("view.bands",this.rebuildMaterial,this),this.scene.contentRoot.removeChild(this.entity),this.scene.boundDirty=!0}serialize(t){t.packa(this.entity.getWorldTransform().data),t.pack(this.changedCounter),t.pack(this.visible),t.pack(this.tintClr.r,this.tintClr.g,this.tintClr.b),t.pack(this.temperature,this.saturation,this.brightness,this.blackPoint,this.whitePoint,this.transparency)}onPreRender(){const t=this.scene.events,e=this.scene.camera.renderOverlays&&t.invoke("selection")===this,i=t.invoke("camera.mode"),s=t.invoke("camera.overlay"),n=this.entity.gsplat.instance.material;n.setParameter("mode","rings"===i?1:0),n.setParameter("ringSize",e&&s&&"rings"===i?.04:0);const r=e&&!t.invoke("view.outlineSelection")?this.selectionAlpha:0,a=t.invoke("selectedClr"),o=t.invoke("unselectedClr"),l=t.invoke("lockedClr");n.setParameter("selectedClr",[a.r,a.g,a.b,a.a*r]),n.setParameter("unselectedClr",[o.r,o.g,o.b,o.a]),n.setParameter("lockedClr",[l.r,l.g,l.b,l.a]);const h=-this.blackPoint+this.brightness,c=1/(this.whitePoint-this.blackPoint);if(n.setParameter("clrOffset",[h,h,h]),n.setParameter("clrScale",[c*this.tintClr.r*(1+this.temperature),c*this.tintClr.g,c*this.tintClr.b*(1-this.temperature),this.transparency]),n.setParameter("saturation",this.saturation),n.setParameter("transformPalette",this.transformPalette.texture),this.visible&&e&&t.invoke("camera.bound")){const t=this.localBound,e=(new rt).setTRS(t.center,at.IDENTITY,t.halfExtents);e.mul2(this.entity.getWorldTransform(),e);for(let t=0;t<uk.length/2;t++){const i=uk[2*t],s=uk[2*t+1];e.transformPoint(i,ck),e.transformPoint(s,dk),this.scene.app.drawLine(ck,dk,H.WHITE,!0,this.scene.debugLayer)}}this.entity.enabled=this.visible}focalPoint(){return this.worldBound.center}move(t,e,i){const s=this.entity;t&&s.setLocalPosition(t),e&&s.setLocalRotation(e),i&&s.setLocalScale(i),this.makeWorldBoundDirty(),this.scene.events.fire("splat.moved",this)}makeSelectionBoundDirty(){this.selectionBoundDirty=!0,this.makeLocalBoundDirty()}makeLocalBoundDirty(){this.localBoundDirty=!0,this.makeWorldBoundDirty()}makeWorldBoundDirty(){this.worldBoundDirty=!0,this.scene.boundDirty=!0}get selectionBound(){const t=this.selectionBoundStorage;return this.selectionBoundDirty&&(this.scene.dataProcessor.calcBound(this,t,!0),this.selectionBoundDirty=!1),t}get localBound(){const t=this.localBoundStorage;return this.localBoundDirty&&(this.scene.dataProcessor.calcBound(this,t,!1),this.localBoundDirty=!1,this.entity.getWorldTransform().transformPoint(t.center,hk)),t}get worldBound(){const t=this.worldBoundStorage;return this.worldBoundDirty&&(t.setFromTransformedAabb(this.localBound,this.entity.getWorldTransform()),this.worldBoundDirty=!1),t}set visible(t){t!==this.visible&&(this._visible=t,this.scene.events.fire("splat.visibility",this))}get visible(){return this._visible}set tintClr(t){this._tintClr.equals(t)||(this._tintClr.set(t.r,t.g,t.b),this.scene.events.fire("splat.tintClr",this))}get tintClr(){return this._tintClr}set temperature(t){t!==this._temperature&&(this._temperature=t,this.scene.events.fire("splat.temperature",this))}get temperature(){return this._temperature}set saturation(t){t!==this._saturation&&(this._saturation=t,this.scene.events.fire("splat.saturation",this))}get saturation(){return this._saturation}set brightness(t){t!==this._brightness&&(this._brightness=t,this.scene.events.fire("splat.brightness",this))}get brightness(){return this._brightness}set blackPoint(t){t!==this._blackPoint&&(this._blackPoint=t,this.scene.events.fire("splat.blackPoint",this))}get blackPoint(){return this._blackPoint}set whitePoint(t){t!==this._whitePoint&&(this._whitePoint=t,this.scene.events.fire("splat.whitePoint",this))}get whitePoint(){return this._whitePoint}set transparency(t){t!==this._transparency&&(this._transparency=t,this.scene.events.fire("splat.transparency",this))}get transparency(){return this._transparency}getPivot(t,e,i){const{entity:s}=this;switch(t){case"center":i.set(s.getLocalPosition(),s.getLocalRotation(),s.getLocalScale());break;case"boundCenter":s.getLocalTransform().transformPoint((e?this.selectionBound:this.localBound).center,hk),i.set(hk,s.getLocalRotation(),s.getLocalScale())}}docSerialize(){const t=t=>[t.x,t.y,t.z];return{name:this.name,position:t(this.entity.getLocalPosition()),rotation:(t=>[t.x,t.y,t.z,t.w])(this.entity.getLocalRotation()),scale:t(this.entity.getLocalScale()),visible:this.visible,tintClr:(t=>[t.r,t.g,t.b,t.a])(this.tintClr),temperature:this.temperature,saturation:this.saturation,brightness:this.brightness,blackPoint:this.blackPoint,whitePoint:this.whitePoint,transparency:this.transparency}}docDeserialize(t){const{name:e,position:i,rotation:s,scale:n,visible:r,tintClr:a,temperature:o,saturation:l,brightness:h,blackPoint:c,whitePoint:d,transparency:u}=t;this.name=e,this.move(new K(i),new at(s),new K(n)),this.visible=r,this.tintClr=new H(a[0],a[1],a[2],a[3]),this.temperature=o??0,this.saturation=l??1,this.brightness=h,this.blackPoint=c,this.whitePoint=d,this.transparency=u}}const fk=new K(0,0,180),mk=new K(90,0,180);class _k{constructor(t,e,i){this.loadAllData=!0,this.app=t,this.events=e,this.defaultAnisotropy=i||1}async load(t){const e=e=>{const i=new T_(t.filename||t.url,"gsplat",{url:t.contents?`local-asset-${Date.now()}`:t.url??t.filename,filename:t.filename});return this.app.assets.add(i),i.resource=new Rm(this.app.graphicsDevice,e),i};t.animationFrame||this.events.fire("startSpinner");try{const i=(t.filename||t.url).toLowerCase();let s,n=fk;return i.endsWith(".splat")?s=e(await tk(t)):i.endsWith(".lcc")?(s=e(await Jz(t)),n=mk):s=await((t,e)=>{const i=e.contents&&(e.contents instanceof Response?e.contents:new Response(e.contents)),s={url:i?"local-asset-"+Bz++:e.url??e.filename,filename:e.filename,contents:i},n={decompress:!0,reorder:!e.animationFrame},r={mapUrl:e.mapUrl};return new Promise((i,a)=>{const o=new T_(e.filename||e.url,"gsplat",s,n,r);o.on("load:data",t=>{if(t instanceof ym&&t.getProp("scale_0")&&t.getProp("scale_1")&&!t.getProp("scale_2")){const e=new Float32Array(t.numSplats).fill(Math.log(1e-6));t.addProp("scale_2",e);const i=t.getElement("vertex").properties;i.splice(i.findIndex(t=>"scale_1"===t.name)+1,0,i.splice(i.length-1,1)[0])}}),o.on("load",()=>{const t=o.resource.gsplatData,e=["x","y","z","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","f_dc_0","f_dc_1","f_dc_2","opacity"].filter(e=>!t.getProp(e));e.length>0?a(new Error(`This file does not contain gaussian splatting data. The following properties are missing: ${e.join(", ")}`)):i(o)}),o.on("error",t=>{a(t)}),t.add(o),t.load(o)})})(this.app.assets,t),new pk(s,n)}finally{t.animationFrame||this.events.fire("stopSpinner")}}}const gk=new K,vk=new K,yk=(t,e)=>{for(const i in e)t.resolve(i).setValue(e[i])};class Sk{constructor(t){this.viewProjectionMat=new rt,this.splatParams=new Int32Array(3),this.device=t,this.dummyTexture=new Gi(t,{width:1,height:1,format:7});const e=(e,i,s,n)=>new Gi(t,{name:e,width:i,height:s,format:n,mipmaps:!1,addressU:1,addressV:1});this.copyShader=th.createShader(t,{uniqueName:"copyShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n ",fragmentGLSL:"\n uniform sampler2D colorTex;\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n gl_FragColor = texelFetch(colorTex, texel, 0);\n }\n "}),this.getIntersectResources=(()=>{let i=null,s=null,n=null,r=null;return(a,o)=>{i||(i=th.createShader(t,{uniqueName:"intersectByMaskShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform uvec2 splat_params; // splat texture width, num splats\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n uniform uvec2 output_params; // output width, height\n\n // 0: mask, 1: rect, 2: sphere\n uniform int mode;\n\n // mask params\n uniform sampler2D mask; // mask in alpha channel\n uniform vec2 mask_params; // mask width, height\n\n // rect params\n uniform vec4 rect_params; // rect x, y, width, height\n\n // sphere params\n uniform vec4 sphere_params; // sphere x, y, z, radius\n\n // box params\n uniform vec4 box_params; // box x, y, z\n uniform vec4 aabb_params; // len x, y, z\n\n void main(void) {\n // calculate output id\n uvec2 outputUV = uvec2(gl_FragCoord);\n uint outputId = (outputUV.x + outputUV.y * output_params.x) * 4u;\n\n vec4 clr = vec4(0.0);\n\n for (uint i = 0u; i < 4u; i++) {\n uint id = outputId + i;\n\n if (id >= splat_params.y) {\n continue;\n }\n\n // calculate splatUV\n ivec2 splatUV = ivec2(\n int(id % splat_params.x),\n int(id / splat_params.x)\n );\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n // transform to clip space and discard if outside\n vec3 world = (matrix_model * vec4(center, 1.0)).xyz;\n vec4 clip = matrix_viewProjection * vec4(world, 1.0);\n vec3 ndc = clip.xyz / clip.w;\n\n // skip offscreen fragments\n if (!any(greaterThan(abs(ndc), vec3(1.0)))) {\n if (mode == 0) {\n // select by mask\n ivec2 maskUV = ivec2((ndc.xy * vec2(0.5, -0.5) + 0.5) * mask_params);\n clr[i] = texelFetch(mask, maskUV, 0).a < 1.0 ? 0.0 : 1.0;\n } else if (mode == 1) {\n // select by rect\n clr[i] = all(greaterThan(ndc.xy * vec2(1.0, -1.0), rect_params.xy)) && all(lessThan(ndc.xy * vec2(1.0, -1.0), rect_params.zw)) ? 1.0 : 0.0;\n } else if (mode == 2) {\n // select by sphere\n clr[i] = length(world - sphere_params.xyz) < sphere_params.w ? 1.0 : 0.0;\n } else if (mode == 3) {\n // select by box\n vec3 relativePosition = world - box_params.xyz;\n bool isInsideCube = true;\n if (relativePosition.x < -aabb_params.x || relativePosition.x > aabb_params.x) {\n isInsideCube = false;\n }\n if (relativePosition.y < -aabb_params.y || relativePosition.y > aabb_params.y) {\n isInsideCube = false;\n }\n if (relativePosition.z < -aabb_params.z || relativePosition.z > aabb_params.z) {\n isInsideCube = false;\n }\n clr[i] = isInsideCube ? 1.0 : 0.0;\n }\n }\n }\n\n gl_FragColor = clr;\n }\n"}));const l=Math.max(1,Math.floor(a/2)),h=Math.ceil(o/(4*l));return s&&s.width===l&&s.height===h||(s&&(s.destroy(),n.destroy()),s=e("intersectTexture",l,h,7),n=new Ss({colorBuffer:s,depth:!1}),r=new Uint8Array(l*h*4)),{shader:i,texture:s,renderTarget:n,data:r}}})(),this.getBoundResources=(()=>{let i=null,s=null,n=null,r=null,a=null,o=null,l=null,h=null;return c=>(i||(i=th.createShader(t,{uniqueName:"calcBoundShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform sampler2D splatState; // per-splat state\n uniform highp ivec3 splat_params; // texture width, texture height, num splats\n uniform highp uint mode; // 0: selected, 1: visible\n\n // calculate min and max for a single column of splats\n void main(void) {\n\n vec3 boundMin = vec3(1e6);\n vec3 boundMax = vec3(-1e6);\n\n for (int id = 0; id < splat_params.y; id++) {\n // calculate splatUV\n ivec2 splatUV = ivec2(gl_FragCoord.x, id);\n\n // skip out-of-range splats\n if ((splatUV.x + splatUV.y * splat_params.x) >= splat_params.z) {\n continue;\n }\n\n // read splat state\n uint state = uint(texelFetch(splatState, splatUV, 0).r * 255.0);\n\n // skip deleted or locked splats\n if (((mode == 0u) && (state != 1u)) || ((mode == 1u) && ((state & 4u) != 0u))) {\n continue;\n }\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n boundMin = min(boundMin, mix(center, boundMin, isinf(center)));\n boundMax = max(boundMax, mix(center, boundMax, isinf(center)));\n }\n\n pcFragColor0 = vec4(boundMin, 0.0);\n pcFragColor1 = vec4(boundMax, 0.0);\n }\n"})),s&&s.width===c||(s&&(s.destroy(),n.destroy(),r.destroy(),a.destroy(),o.destroy()),s=e("calcBoundMin",c,1,Nt),n=e("calcBoundMax",c,1,Nt),r=new Ss({colorBuffers:[s,n],depth:!1}),o=new Ss({colorBuffer:n,depth:!1}),a=new Ss({colorBuffer:s,depth:!1}),l=new Float32Array(4*c),h=new Float32Array(4*c)),{shader:i,minTexture:s,maxTexture:n,renderTarget:r,minRenderTarget:a,maxRenderTarget:o,minData:l,maxData:h})})(),this.getPositionResources=(()=>{let i=null,s=null,n=null,r=null;return(a,o,l)=>(i||(i=th.createShader(t,{uniqueName:"calcPositionShader",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform highp usampler2D transformA; // splat center x, y, z\n uniform highp usampler2D splatTransform; // transform palette index\n uniform sampler2D transformPalette; // palette of transforms\n uniform ivec2 splat_params; // splat texture width, num splats\n\n void main(void) {\n // calculate output id\n ivec2 splatUV = ivec2(gl_FragCoord);\n\n // skip if splat index is out of bounds\n if (splatUV.x + splatUV.y * splat_params.x >= splat_params.y) {\n discard;\n }\n\n // read splat center\n vec3 center = uintBitsToFloat(texelFetch(transformA, splatUV, 0).xyz);\n\n // apply optional per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat3x4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n\n center = vec4(center, 1.0) * t;\n }\n\n gl_FragColor = vec4(center, 0.0);\n }\n"})),s&&s.width===a&&s.height===o||(s&&(s.destroy(),n.destroy()),s=e("positionTex",a,o,Nt),n=new Ss({colorBuffer:s,depth:!1}),r=new Float32Array(a*o*4)),{shader:i,texture:s,renderTarget:n,data:r})})()}intersect(t,e){const{device:i}=this,{scope:s}=i,n=e.splatData.numSplats,r=e.entity.gsplat.instance.resource.transformATexture,a=e.transformTexture,o=e.transformPalette.texture,l=e.scene.camera.entity.camera;this.viewProjectionMat.mul2(l.projectionMatrix,l.viewMatrix);const h=this.getIntersectResources(r.width,n);yk(s,{transformA:r,splatTransform:a,transformPalette:o,splat_params:[r.width,n],matrix_model:e.entity.getWorldTransform().data,matrix_viewProjection:this.viewProjectionMat.data,output_params:[h.texture.width,h.texture.height]});const c=t;c.mask?yk(s,{mode:0,mask:c.mask,mask_params:[c.mask.width,c.mask.height]}):yk(s,{mask:this.dummyTexture,mask_params:[0,0]});const d=t;d.rect?yk(s,{mode:1,rect_params:[2*d.rect.x1-1,2*d.rect.y1-1,2*d.rect.x2-1,2*d.rect.y2-1]}):yk(s,{rect_params:[0,0,0,0]});const u=t;u.sphere?yk(s,{mode:2,sphere_params:[u.sphere.x,u.sphere.y,u.sphere.z,u.sphere.radius]}):yk(s,{sphere_params:[0,0,0,0]});const p=t;p.box?yk(s,{mode:3,box_params:[p.box.x,p.box.y,p.box.z,0],aabb_params:[.5*p.box.lenx,.5*p.box.leny,.5*p.box.lenz,0]}):yk(s,{box_params:[0,0,0,0],aabb_params:[0,0,0,0]}),i.setBlendState(Ji.NOBLEND),lh(i,h.renderTarget,h.shader);return i.readPixels(0,0,h.texture.width,h.texture.height,h.data),h.data}calcBound(t,e,i){const s=t.scene.graphicsDevice,{scope:n}=s,r=t.splatData.numSplats,a=t.entity.gsplat.instance.resource.transformATexture,o=t.transformTexture,l=t.transformPalette.texture,h=t.stateTexture;this.splatParams[0]=a.width,this.splatParams[1]=a.height,this.splatParams[2]=r;const c=this.getBoundResources(a.width);yk(n,{transformA:a,splatTransform:o,transformPalette:l,splatState:h,splat_params:this.splatParams,mode:i?0:1});const d=s;s.setBlendState(Ji.NOBLEND),lh(s,c.renderTarget,c.shader),d.gl.readPixels(0,0,a.width,1,c.minTexture.impl._glFormat,c.minTexture.impl._glPixelType,c.minData),d.setRenderTarget(c.maxRenderTarget),d.updateBegin(),d.gl.readPixels(0,0,a.width,1,c.maxTexture.impl._glFormat,c.maxTexture.impl._glPixelType,c.maxData),d.updateEnd();const{minData:u,maxData:p}=c;gk.set(1/0,1/0,1/0),vk.set(-1/0,-1/0,-1/0);for(let t=0;t<a.width;t++){const e=u[4*t],i=u[4*t+1],s=u[4*t+2];isFinite(e)&&(gk.x=Math.min(gk.x,e)),isFinite(i)&&(gk.y=Math.min(gk.y,i)),isFinite(s)&&(gk.z=Math.min(gk.z,s));const n=p[4*t],r=p[4*t+1],a=p[4*t+2];isFinite(n)&&(vk.x=Math.max(vk.x,n)),isFinite(r)&&(vk.y=Math.max(vk.y,r)),isFinite(a)&&(vk.z=Math.max(vk.z,a))}e.setMinMax(gk,vk)}calcPositions(t){const{device:e}=this,{scope:i}=e,s=t.splatData.numSplats,n=t.entity.gsplat.instance.resource.transformATexture,r=t.transformTexture,a=t.transformPalette.texture,o=this.getPositionResources(n.width,n.height,s);yk(i,{transformA:n,splatTransform:r,transformPalette:a,splat_params:[n.width,s]}),e.setBlendState(Ji.NOBLEND),lh(e,o.renderTarget,o.shader);return e.gl.readPixels(0,0,o.texture.width,o.texture.height,o.texture.impl._glFormat,o.texture.impl._glPixelType,o.data),o.data}copyRt(t,e){const{device:i}=this;yk(i.scope,{colorTex:t.colorBuffer}),i.setBlendState(Ji.NOBLEND),lh(i,e,this.copyShader)}}class xk extends R{constructor(){super(...arguments),this.functions=new Map}function(t,e){if(this.functions.has(t))throw new Error(`error: function ${t} already exists`);this.functions.set(t,e)}invoke(t,...e){const i=this.functions.get(t);if(i)return i(...e)}}const Tk=new K,Ek=new K,bk=new K,wk=(t,e,i,s)=>Math.sqrt((i-t)**2+(s-e)**2);class Ak{constructor(t,e){const i=(e,i)=>{const s=t.azim-e*t.scene.config.controls.orbitSensitivity,n=t.elevation-i*t.scene.config.controls.orbitSensitivity;t.setAzimElev(s,n)},s=(e,i,s,n)=>{const r=t.entity.camera,a=t.distanceTween.value.distance*t.sceneRadius/t.fovFactor;r.screenToWorld(e,i,a,Tk),r.screenToWorld(e-s,i-n,a,Ek),bk.sub2(Ek,Tk),bk.add(t.focalPoint),t.setFocalPoint(bk)},n=e=>{t.setDistance(t.distance-(.999*t.distance+.001)*e*t.scene.config.controls.zoomSensitivity,2)};let r,a,o=-1;const l=new Set;let h,c,d,u=[];const p={ArrowUp:0,ArrowDown:0,ArrowLeft:0,ArrowRight:0};let f=!0,m=!0,_=!0,g=!0;const v=t.scene.app.graphicsDevice.canvas;this.update=e=>{const i=p.ArrowRight-p.ArrowLeft,s=p.ArrowDown-p.ArrowUp;if(i||s){const n=e*t.flySpeed,r=t.entity.getWorldTransform(),a=r.getX().mulScalar(i*n),o=r.getZ().mulScalar(s*n),l=t.focalPoint.add(a).add(o);t.setFocalPoint(l)}};let y=null;const S=(e,i,s,n)=>{const r=e=>{t.scene.events.fire("camera.controller",i),s(e)};e.addEventListener(i,r,n),y=()=>{y?.(),e.removeEventListener(i,r)}};S(e,"pointerdown",t=>{if(f)if("mouse"===t.pointerType){if(-1!==o)return;e.setPointerCapture(t.pointerId),l.add(t.pointerId),o=t.button,r=t.offsetX,a=t.offsetY}else"touch"===t.pointerType&&(0===u.length&&(e.setPointerCapture(t.pointerId),l.add(t.pointerId)),u.push({x:t.offsetX,y:t.offsetY,id:t.pointerId}),2===u.length&&(h=.5*(u[0].x+u[1].x),c=.5*(u[0].y+u[1].y),d=wk(u[0].x,u[0].y,u[1].x,u[1].y)))}),S(e,"pointerup",t=>{if(!f){if(l.has(t.pointerId)){try{e.releasePointerCapture(t.pointerId)}catch{}l.delete(t.pointerId)}return o=-1,void(u=u.filter(e=>e.id!==t.pointerId))}"mouse"===t.pointerType?t.button===o&&(o=-1,e.releasePointerCapture(t.pointerId),l.delete(t.pointerId)):(u=u.filter(e=>e.id!==t.pointerId),0===u.length&&(e.releasePointerCapture(t.pointerId),l.delete(t.pointerId)))}),S(e,"pointermove",t=>{if(f)if("mouse"===t.pointerType){if(-1===o)return;const e=[1,4,2][o];if(0===(t.buttons&e))return void(o=-1);const l=t.offsetX-r,h=t.offsetY-a;r=t.offsetX,a=t.offsetY;const c=2===o?t.shiftKey||t.ctrlKey?"orbit":t.altKey||t.metaKey?"zoom":null:null;("orbit"===c||null===c&&0===o)&&m?i(l,h):("zoom"===c||null===c&&1===o)&&g?n(-.02*h):("pan"===c||null===c&&2===o)&&_&&s(r,a,l,h)}else if(1===u.length){const e=u[0],s=t.offsetX-e.x,n=t.offsetY-e.y;e.x=t.offsetX,e.y=t.offsetY,m&&i(s,n)}else if(2===u.length){const e=u[u.map(t=>t.id).indexOf(t.pointerId)];e.x=t.offsetX,e.y=t.offsetY;const i=.5*(u[0].x+u[1].x),r=.5*(u[0].y+u[1].y),a=wk(u[0].x,u[0].y,u[1].x,u[1].y);_&&s(i,r,i-h,r-c),g&&n(.01*(a-d)),h=i,c=r,d=a}}),S(e,"wheel",t=>{if(!f)return;const{deltaX:e,deltaY:r}=t;((t,e)=>Math.abs(t)>50&&0===e||Math.abs(e)>50&&0===t||0===t&&0!==e&&!Number.isInteger(e))(e,r)?g&&n(-.002*r):t.ctrlKey||t.metaKey?g&&n(-.02*r):t.shiftKey?_&&s(t.offsetX,t.offsetY,e,r):m&&i(e,r),t.preventDefault()},{passive:!1}),S(e,"dblclick",i=>{f&&(i.target!==e&&i.target!==v||t.pickFocalPoint(i.offsetX,i.offsetY))}),S(document,"keydown",t=>{f&&p.hasOwnProperty(t.key)&&t.target===document.body&&(p[t.key]=t.shiftKey?10:t.ctrlKey||t.metaKey||t.altKey?.1:1)}),S(document,"keyup",t=>{f&&p.hasOwnProperty(t.key)&&(p[t.key]=0)}),this.destroy=y,this.setEnabled=t=>{const i=!!t;i!==f&&(f=i,f||(()=>{o=-1,u=[];for(const t in p)p[t]=0;l.forEach(t=>{try{e.releasePointerCapture(t)}catch{}}),l.clear()})())},this.setInputControls=t=>{void 0!==t.orbit&&(m=!!t.orbit),void 0!==t.pan&&(_=!!t.pan),void 0!==t.zoom&&(g=!!t.zoom)}}}const Ck=t=>Math.pow(t-1,5)+1;class Mk{constructor(t){this.keys=Object.keys(t)}clone(t){const e={};return this.keys.forEach(i=>{e[i]=t[i]}),e}copy(t,e){this.keys.forEach(i=>{t[i]=e[i]})}lerp(t,e,i,s){this.keys.forEach(n=>{t[n]=e[n]+s*(i[n]-e[n])})}}class Pk{constructor(t){this.ops=new Mk(t),this.value=t,this.source=this.ops.clone(t),this.target=this.ops.clone(t),this.timer=0,this.transitionTime=0}goto(t,e=.25){0===e&&this.ops.copy(this.value,t),this.ops.copy(this.source,this.value),this.ops.copy(this.target,t),this.timer=0,this.transitionTime=e}update(t){this.timer<this.transitionTime?(this.timer=Math.min(this.timer+t,this.transitionTime),this.ops.lerp(this.value,this.source,this.target,Ck(this.timer/this.transitionTime))):this.ops.copy(this.value,this.target)}}const Rk=new K,Lk=new K,Dk=new _t,Ik=new vt,Ok=new K,Nk=new K,Fk=new K,Uk=new rt,Bk=new J;class zk extends nk{constructor(){super(ek.camera),this.focalPointTween=new Pk({x:0,y:.5,z:0}),this.azimElevTween=new Pk({azim:30,elev:-15}),this.distanceTween=new Pk({distance:1}),this.minElev=-90,this.maxElev=90,this.sceneRadius=1,this.flySpeed=5,this.targetSize=null,this.suppressFinalBlit=!1,this.renderOverlays=!0,this.manualControl=!1,this.entity=new z_("Camera"),this.entity.addComponent("camera")}set ortho(t){t!==this.ortho&&(this.entity.camera.projection=t?1:0,this.scene.events.fire("camera.ortho",t))}get ortho(){return 1===this.entity.camera.projection}set fov(t){this.entity.camera.fov=t}get fov(){return this.entity.camera.fov}set tonemapping(t){const e={none:6,linear:0,neutral:5,aces:3,aces2:4,filmic:1,hejl:2}[t];void 0!==e&&e!==this.entity.camera.toneMapping&&(this.entity.camera.toneMapping=e,this.scene.events.fire("camera.tonemapping",t))}get tonemapping(){switch(this.entity.camera.toneMapping){case 6:return"none";case 0:return"linear";case 5:return"neutral";case 3:return"aces";case 4:return"aces2";case 1:return"filmic";case 2:return"hejl"}return"none"}set near(t){this.entity.camera.nearClip=t}get near(){return this.entity.camera.nearClip}set far(t){this.entity.camera.farClip=t}get far(){return this.entity.camera.farClip}get focalPoint(){const t=this.focalPointTween.target;return new K(t.x,t.y,t.z)}get azimElev(){return this.azimElevTween.target}get azim(){return this.azimElev.azim}get elevation(){return this.azimElev.elev}get distance(){return this.distanceTween.target.distance}setFocalPoint(t,e=1){this.focalPointTween.goto(t,e*this.scene.config.controls.dampingFactor)}setAzimElev(t,e,i=1){t=((t,e)=>(t%e+e)%e)(t,360),e=Math.max(this.minElev,Math.min(this.maxElev,e));const s=this.azimElevTween;s.goto({azim:t,elev:e},i*this.scene.config.controls.dampingFactor),s.source.azim-t<-180?s.source.azim+=360:s.source.azim-t>180&&(s.source.azim-=360),this.ortho=!1}setDistance(t,e=1){const i=this.scene.config.controls;t=Math.max(i.minZoom,Math.min(i.maxZoom,t));this.distanceTween.goto({distance:t},e*i.dampingFactor)}setPose(t,e,i=1){Ok.sub2(e,t);const s=Ok.length(),n=Math.atan2(-Ok.x/s,-Ok.z/s)*V.RAD_TO_DEG,r=Math.asin(Ok.y/s)*V.RAD_TO_DEG;this.setFocalPoint(e,i),this.setAzimElev(n,r,i),this.setDistance(s/this.sceneRadius*this.fovFactor,i)}worldToScreen(t,e){const{camera:i}=this.entity.camera;Uk.mul2(i.projectionMatrix,i.viewMatrix),Bk.set(t.x,t.y,t.z,1),Uk.transformVec4(Bk,Bk),e.x=Bk.x/Bk.w*.5+.5,e.y=1-(Bk.y/Bk.w*.5+.5),e.z=Bk.z/Bk.w}add(){this.scene.cameraRoot.addChild(this.entity),this.entity.camera.layers=this.entity.camera.layers.concat([this.scene.shadowLayer.id,this.scene.debugLayer.id,this.scene.gizmoLayer.id]),this.scene.config.camera.debugRender&&this.entity.camera.setShaderPass(`debug_${this.scene.config.camera.debugRender}`);const t=document.getElementById("canvas-container")??(this.scene?this.scene.app.graphicsDevice.canvas:null);if(!t)throw new Error("Camera: no pointer target available for PointerController");this.controller=new Ak(this,t);const e=this.scene.config,i=e.controls;this.entity.camera.clearColor.set(0,0,0,0),this.minElev=180*i.minPolarAngle/Math.PI-90,this.maxElev=180*i.maxPolarAngle/Math.PI-90,this.scene.camera.entity.camera.toneMapping={linear:0,filmic:1,hejl:2,aces:3,aces2:4,neutral:5}[e.camera.toneMapping],this.scene.app.scene.exposure=e.camera.exposure,this.fov=e.camera.fov,this.setAzimElev(i.initialAzim,i.initialElev,0),this.setDistance(i.initialZoom,0);const{width:s,height:n}=this.scene.targetSize;this.picker=new SC(this.scene.app,s,n),this.picker.allocateRenderTarget=()=>{},this.picker.releaseRenderTarget=()=>{},this.scene.events.on("scene.boundChanged",this.onBoundChanged,this),this.updateCameraUniforms=()=>{const t=this.scene.graphicsDevice,e=this.entity,i=e.camera,s=(e,i)=>{t.scope.resolve(e).setValue([i.x,i.y,i.z])},n=i.camera.getFrustumCorners(-100),r=e.getWorldTransform();for(let t=0;t<n.length;t++)r.transformPoint(n[t],n[t]);0===i.projection?(s("near_origin",r.getTranslation()),s("near_x",K.ZERO),s("near_y",K.ZERO)):(s("near_origin",n[3]),s("near_x",Fk.sub2(n[0],n[3])),s("near_y",Fk.sub2(n[2],n[3]))),s("far_origin",n[7]),s("far_x",Fk.sub2(n[4],n[7])),s("far_y",Fk.sub2(n[6],n[7]))};const r=new URL(location.href),a=r.searchParams.get("focal");if(a){const t=a.toString().split(",");3===t.length&&this.setFocalPoint(new K(parseFloat(t[0]),parseFloat(t[1]),parseFloat(t[2])),0)}const o=r.searchParams.get("angles");if(o){const t=o.toString().split(",");2===t.length&&this.setAzimElev(parseFloat(t[0]),parseFloat(t[1]),0)}const l=r.searchParams.get("distance");l&&this.setDistance(parseFloat(l),0)}remove(){this.controller.destroy(),this.controller=null,this.entity.camera.layers=this.entity.camera.layers.filter(t=>t!==this.scene.shadowLayer.id),this.scene.cameraRoot.removeChild(this.entity),this.picker=null,this.scene.events.off("scene.boundChanged",this.onBoundChanged,this)}onBoundChanged(t){const e=this.distanceTween.value.distance*this.sceneRadius;this.sceneRadius=Math.max(.001,t.halfExtents.length()),this.setDistance(e/this.sceneRadius,0)}serialize(t){t.packa(this.entity.getWorldTransform().data),t.pack(this.fov,this.tonemapping,this.entity.camera.renderTarget?.width,this.entity.camera.renderTarget?.height)}rebuildRenderTargets(){const t=this.scene.graphicsDevice,{width:e,height:i}=this.targetSize??this.scene.targetSize,s=this.scene.events.invoke("camera.highPrecision")?Ot:7,n=this.entity.camera.renderTarget;if(n&&n.width===e&&n.height===i&&n.colorBuffer.format===s)return;n&&(n.destroyTextureBuffers(),n.destroy(),this.workRenderTarget.destroy(),this.workRenderTarget=null);const r=(e,i,s,n)=>new Gi(t,{name:e,width:i,height:s,format:n,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1}),a=r("cameraColor",e,i,s),o=r("cameraDepth",e,i,Ut),l=new Ss({colorBuffer:a,depthBuffer:o,flipY:!1,autoResolve:!1});this.entity.camera.renderTarget=l,this.entity.camera.horizontalFov=e>i;const h=r("workColor",e,i,7);this.workRenderTarget=new Ss({colorBuffer:h,depth:!1,autoResolve:!1}),this.picker.renderTarget=this.workRenderTarget,this.scene.events.fire("camera.resize",{width:e,height:i})}onUpdate(t){if(this.manualControl)return this.fitClippingPlanes(this.entity.getLocalPosition(),this.entity.forward),void this.entity.camera.camera._updateViewProjMat();this.controller.update(t),this.focalPointTween.update(t),this.azimElevTween.update(t),this.distanceTween.update(t);const e=this.azimElevTween.value,i=this.distanceTween.value;((t,e,i)=>{const s=i*V.DEG_TO_RAD,n=e*V.DEG_TO_RAD,r=Math.sin(-s),a=Math.cos(-s),o=Math.sin(-n),l=Math.cos(-n);t.set(-a*o,r,a*l)})(Rk,e.azim,e.elev),Lk.copy(Rk),Lk.mulScalar(i.distance*this.sceneRadius/this.fovFactor),Lk.add(this.focalPointTween.value),this.entity.setLocalPosition(Lk),this.entity.setLocalEulerAngles(e.elev,e.azim,0),this.fitClippingPlanes(this.entity.getLocalPosition(),this.entity.forward);const{camera:s}=this.entity;s.orthoHeight=this.distanceTween.value.distance*this.sceneRadius/this.fovFactor*(this.fov/90)*(s.horizontalFov?this.scene.targetSize.height/this.scene.targetSize.width:1),s.camera._updateViewProjMat()}setManualControl(t){this.manualControl=!!t;try{this.controller?.setEnabled?.(!this.manualControl)}catch{}}fitClippingPlanes(t,e){const i=this.scene.bound,s=i.halfExtents.length();Ok.sub2(i.center,t);const n=Ok.dot(e);n>0?(this.far=n+s,this.near=Math.max(1e-6,n<s?this.far/16384:n-s)):(this.far=2*s,this.near=this.far/16384)}onPreRender(){this.rebuildRenderTargets(),this.updateCameraUniforms()}onPostRender(){const t=this.scene.graphicsDevice,e=this.entity.camera.renderTarget;e.samples>1&&e.resolve(!0,!1),this.suppressFinalBlit||t.copyRenderTarget(e,null,!0,!1)}focus(t){const e=t?t.focalPoint:(()=>{for(const t of this.scene.elements)if(t.type===ek.splat){const e=t.focalPoint?.();if(e)return e}})()??this.scene.bound.center,i=(t?t.radius:this.scene.bound.halfExtents.length())/this.sceneRadius;this.setDistance(isFinite(i)?i:1,t?.speed??0),this.setFocalPoint(e,t?.speed??0)}get fovFactor(){const{width:t,height:e}=this.scene.targetSize,i=t&&e?this.entity.camera.horizontalFov?e/t:t/e:1,s=2*Math.atan(Math.tan(this.fov*V.DEG_TO_RAD*.5)*i);return Math.sin(.5*s)}getRay(t,e,i){const{entity:s,ortho:n,scene:r}=this,a=this.entity.getPosition();n?(s.camera.screenToWorld(t,e,-1,Ok),s.camera.screenToWorld(t,e,1,Nk),Nk.sub(Ok).normalize(),i.set(Ok,Nk)):(s.camera.screenToWorld(t,e,1,Ok),Ok.sub(a).normalize(),i.set(a,Ok))}intersect(t,e){const{scene:i}=this,s=i.canvas,n=t/s.clientWidth*i.targetSize.width,r=e/s.clientHeight*i.targetSize.height;this.getRay(t,e,Ik);const a=i.getElementsByType(ek.splat);let o=0;const l=new K;let h=null;for(let t=0;t<a.length;++t){const e=a[t];this.pickPrep(e,"set");const i=this.pick(n,r);if(-1!==i&&(e.calcSplatWorldPosition(i,Ok),Dk.setFromPointNormal(Ok,this.entity.forward),Dk.intersectsRay(Ik,Ok))){const t=Nk.sub2(Ok,Ik.origin).length();(!h||t<o)&&(o=t,l.copy(Ok),h=e)}}return h?{splat:h,position:l,distance:o}:null}pickFocalPoint(t,e){const i=this.intersect(t,e);if(i){const{scene:t}=this;this.setFocalPoint(i.position),this.setDistance(i.distance/this.sceneRadius*this.fovFactor),t.events.fire("camera.focalPointPicked",{camera:this,splat:i.splat,position:i.position})}}pickPrep(t,e){const{width:i,height:s}=this.scene.targetSize,n=this.scene.app.scene.layers.getLayerByName("World"),r=this.scene.graphicsDevice,a="rings"===this.scene.events.invoke("camera.mode")?0:.2,o=this.scene.getElementsByType(ek.splat);o.forEach(e=>{e.entity.enabled=e===t}),r.scope.resolve("pickerAlpha").setValue(a),r.scope.resolve("pickMode").setValue(["add","remove","set"].indexOf(e)),this.picker.resize(i,s),this.picker.prepare(this.entity.camera,this.scene.app.scene,[n]),o.forEach(t=>{t.entity.enabled=!0})}pick(t,e){return this.pickRect(t,e,1,1)[0]}pickRect(t,e,i,s){const n=this.scene.graphicsDevice,r=new Uint8Array(i*s*4);n.setRenderTarget(this.picker.renderTarget),n.updateBegin(),n.readPixels(t,this.picker.renderTarget.height-e-s,i,s,r),n.updateEnd();const a=[];for(let t=0;t<i*s;t++)a.push(r[4*t]|r[4*t+1]<<8|r[4*t+2]<<16|r[4*t+3]<<24);return a}docSerialize(){return{focalPoint:(t=>[t.x,t.y,t.z])(this.focalPointTween.target),azim:this.azim,elev:this.elevation,distance:this.distance,fov:this.fov,tonemapping:this.tonemapping}}docDeserialize(t){this.setFocalPoint(new K(t.focalPoint),0),this.setAzimElev(t.azim,t.elev,0),this.setDistance(t.distance,0),this.fov=t.fov,this.tonemapping=t.tonemapping}startOffscreenMode(t,e){this.targetSize={width:t,height:e},this.suppressFinalBlit=!0}endOffscreenMode(){this.targetSize=null,this.suppressFinalBlit=!1}}class kk extends nk{constructor(){super(ek.debug),this.blendState=new Ji(!1),this.depthState=new is(3,!0),this.visible=!0}add(){const t=this.scene.app.graphicsDevice;this.shader=th.createShader(t,{uniqueName:"infinite-grid",attributes:{vertex_position:ce},vertexGLSL:"\n uniform vec3 near_origin;\n uniform vec3 near_x;\n uniform vec3 near_y;\n\n uniform vec3 far_origin;\n uniform vec3 far_x;\n uniform vec3 far_y;\n\n attribute vec2 vertex_position;\n\n varying vec3 worldFar;\n varying vec3 worldNear;\n\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n\n vec2 p = vertex_position * 0.5 + 0.5;\n worldNear = near_origin + near_x * p.x + near_y * p.y;\n worldFar = far_origin + far_x * p.x + far_y * p.y;\n }\n",fragmentGLSL:"\n uniform vec3 view_position;\n uniform mat4 matrix_viewProjection;\n uniform sampler2D blueNoiseTex32;\n\n uniform int plane; // 0: x (yz), 1: y (xz), 2: z (xy)\n\n vec4 planes[3] = vec4[3](\n vec4(1.0, 0.0, 0.0, 0.0),\n vec4(0.0, 1.0, 0.0, 0.0),\n vec4(0.0, 0.0, 1.0, 0.0)\n );\n\n vec3 colors[3] = vec3[3](\n vec3(1.0, 0.2, 0.2),\n vec3(0.2, 1.0, 0.2),\n vec3(0.2, 0.2, 1.0)\n );\n\n int axis0[3] = int[3](1, 0, 0);\n int axis1[3] = int[3](2, 2, 1);\n\n varying vec3 worldNear;\n varying vec3 worldFar;\n\n bool intersectPlane(inout float t, vec3 pos, vec3 dir, vec4 plane) {\n float d = dot(dir, plane.xyz);\n if (abs(d) < 1e-06) {\n return false;\n }\n\n float n = -(dot(pos, plane.xyz) + plane.w) / d;\n if (n < 0.0) {\n return false;\n }\n\n t = n;\n\n return true;\n }\n\n // https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8#1e7c\n float pristineGrid(in vec2 uv, in vec2 ddx, in vec2 ddy, vec2 lineWidth) {\n vec2 uvDeriv = vec2(length(vec2(ddx.x, ddy.x)), length(vec2(ddx.y, ddy.y)));\n bvec2 invertLine = bvec2(lineWidth.x > 0.5, lineWidth.y > 0.5);\n vec2 targetWidth = vec2(\n invertLine.x ? 1.0 - lineWidth.x : lineWidth.x,\n invertLine.y ? 1.0 - lineWidth.y : lineWidth.y\n );\n vec2 drawWidth = clamp(targetWidth, uvDeriv, vec2(0.5));\n vec2 lineAA = uvDeriv * 1.5;\n vec2 gridUV = abs(fract(uv) * 2.0 - 1.0);\n gridUV.x = invertLine.x ? gridUV.x : 1.0 - gridUV.x;\n gridUV.y = invertLine.y ? gridUV.y : 1.0 - gridUV.y;\n vec2 grid2 = smoothstep(drawWidth + lineAA, drawWidth - lineAA, gridUV);\n\n grid2 *= clamp(targetWidth / drawWidth, 0.0, 1.0);\n grid2 = mix(grid2, targetWidth, clamp(uvDeriv * 2.0 - 1.0, 0.0, 1.0));\n grid2.x = invertLine.x ? 1.0 - grid2.x : grid2.x;\n grid2.y = invertLine.y ? 1.0 - grid2.y : grid2.y;\n\n return mix(grid2.x, 1.0, grid2.y);\n }\n\n float calcDepth(vec3 p) {\n vec4 v = matrix_viewProjection * vec4(p, 1.0);\n return (v.z / v.w) * 0.5 + 0.5;\n }\n\n bool writeDepth(float alpha) {\n vec2 uv = fract(gl_FragCoord.xy / 32.0);\n float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;\n return alpha > noise;\n }\n\n void main(void) {\n vec3 p = worldNear;\n vec3 v = normalize(worldFar - worldNear);\n\n // intersect ray with the world xz plane\n float t;\n if (!intersectPlane(t, p, v, planes[plane])) {\n discard;\n }\n\n // calculate grid intersection\n vec3 worldPos = p + v * t;\n vec2 pos = plane == 0 ? worldPos.yz : (plane == 1 ? worldPos.xz : worldPos.xy);\n vec2 ddx = dFdx(pos);\n vec2 ddy = dFdy(pos);\n\n float epsilon = 1.0 / 255.0;\n\n // calculate fade\n float fade = 1.0 - smoothstep(400.0, 1000.0, length(worldPos - view_position));\n if (fade < epsilon) {\n discard;\n }\n\n vec2 levelPos;\n float levelSize;\n float levelAlpha;\n\n // 10m grid with colored main axes\n levelPos = pos * 0.1;\n levelSize = 2.0 / 1000.0;\n levelAlpha = pristineGrid(levelPos, ddx * 0.1, ddy * 0.1, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n vec3 color;\n vec2 loc = abs(levelPos);\n if (loc.x < levelSize) {\n if (loc.y < levelSize) {\n color = vec3(1.0);\n } else {\n color = colors[axis1[plane]];\n }\n } else if (loc.y < levelSize) {\n color = colors[axis0[plane]];\n } else {\n color = vec3(0.9);\n }\n gl_FragColor = vec4(color, levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n // 1m grid\n levelPos = pos;\n levelSize = 1.0 / 100.0;\n levelAlpha = pristineGrid(levelPos, ddx, ddy, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n gl_FragColor = vec4(vec3(0.7), levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n // 0.1m grid\n levelPos = pos * 10.0;\n levelSize = 1.0 / 100.0;\n levelAlpha = pristineGrid(levelPos, ddx * 10.0, ddy * 10.0, vec2(levelSize)) * fade;\n if (levelAlpha > epsilon) {\n gl_FragColor = vec4(vec3(0.7), levelAlpha);\n gl_FragDepth = writeDepth(levelAlpha) ? calcDepth(worldPos) : 1.0;\n return;\n }\n\n discard;\n }\n"}),this.quadRender=new rh(this.shader);const e=new Ji(!0,0,6,8,0,1,8),i=[0,0,0],s=new rt;let n;this.scene.camera.entity.camera.on("preRenderLayer",(r,a)=>{const{scene:o}=this;if(this.visible&&r===o.debugLayer&&!a&&o.camera.renderOverlays){const{camera:r}=o;if(t.setBlendState(e),t.setCullMode(0),t.setDepthState(is.WRITEDEPTH),t.setStencilState(null,null),r.ortho){const t=(t,e)=>1-Math.abs(t.dot(e))<.001,e=r.entity.getWorldTransform().getZ();n=t(e,K.RIGHT)?0:t(e,K.BACK)?2:1}else n=1;const a=r.entity.getPosition();i[0]=a.x,i[1]=a.y,i[2]=a.z,s.mul2(r.entity.camera.projectionMatrix,r.entity.camera.viewMatrix),((t,e)=>{for(const i in e)t.resolve(i).setValue(e[i])})(t.scope,{plane:n,view_position:i,matrix_viewProjection:s.data}),this.quadRender.render()}})}remove(){this.shader.destroy(),this.quadRender.destroy()}serialize(t){t.pack(this.visible)}}class Vk extends nk{constructor(){super(ek.other),this.enabled=!0,this.clr=new H(1,1,1,.5),this.entity=new z_("outlineCamera"),this.entity.addComponent("camera"),this.entity.camera.setShaderPass("OUTLINE"),this.entity.camera.clearColor=new H(0,0,0,0)}add(){const t=this.scene.app.graphicsDevice,e=this.scene.overlayLayer.id;this.scene.events.on("selection.changed",(t,i)=>{i&&(i.entity.gsplat.layers=i.entity.gsplat.layers.filter(t=>t!==e)),t&&(t.entity.gsplat.layers=t.entity.gsplat.layers.concat([e]))}),this.entity.camera.layers=[e],this.scene.camera.entity.addChild(this.entity),this.shader=th.createShader(t,{uniqueName:"apply-outline",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform sampler2D outlineTexture;\n uniform float alphaCutoff;\n uniform vec4 clr;\n\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n\n // skip solid pixels\n if (texelFetch(outlineTexture, texel, 0).a > alphaCutoff) {\n discard;\n }\n\n for (int x = -2; x <= 2; x++) {\n for (int y = -2; y <= 2; y++) {\n if ((x != 0) && (y != 0) && (texelFetch(outlineTexture, texel + ivec2(x, y), 0).a > alphaCutoff)) {\n gl_FragColor = clr;\n return;\n }\n }\n }\n\n discard;\n }\n"}),this.quadRender=new rh(this.shader);const i=t.scope.resolve("outlineTexture"),s=t.scope.resolve("alphaCutoff"),n=t.scope.resolve("clr"),r=[1,1,1,1],a=this.scene.events;this.entity.camera.on("postRenderLayer",(e,o)=>{if(!this.entity.enabled||e!==this.scene.overlayLayer||!o)return;t.setBlendState(Ji.ALPHABLEND),t.setCullMode(0),t.setDepthState(is.NODEPTH),t.setStencilState(null,null);const l=a.invoke("selectedClr");r[0]=l.r,r[1]=l.g,r[2]=l.b,r[3]=l.a,i.setValue(this.entity.camera.renderTarget.colorBuffer),s.setValue("rings"===a.invoke("camera.mode")?0:.4),n.setValue(r);const h=t;h.setRenderTarget(this.scene.camera.entity.camera.renderTarget),h.updateBegin(),this.quadRender.render(),h.updateEnd()})}remove(){this.scene.camera.entity.removeChild(this.entity)}onPreRender(){const t=this.scene.camera.entity.camera,e=this.entity.camera;e.projection=t.projection,e.horizontalFov=t.horizontalFov,e.fov=t.fov,e.nearClip=t.nearClip,e.farClip=t.farClip,e.orthoHeight=t.orthoHeight,this.entity.enabled=this.enabled&&this.scene.events.invoke("view.outlineSelection"),this.entity.camera.renderTarget=this.scene.camera.workRenderTarget}}class Hk extends q_{constructor(t,e){super(t);const i=new $_;i.graphicsDevice=e.graphicsDevice,this.addComponentSystems(i),this.addResourceHandles(i),i.elementInput=e.elementInput,i.keyboard=e.keyboard,i.mouse=e.mouse,i.touch=e.touch,i.gamepads=e.gamepads,i.scriptPrefix=e.scriptPrefix,i.assetPrefix=e.assetPrefix,i.scriptsOrder=e.scriptsOrder,this.init(i)}addComponentSystems(t){t.componentSystems=[gv,tx,_T,ST,ME]}addResourceHandles(t){t.resourceHandlers=[IE,Db,Ib,vA,Hb,kb,dw]}}class Gk{constructor(t){this.packValue=t}pack(...t){for(let e=0;e<t.length;++e)this.packValue(t[e])}packa(t){for(let e=0;e<t.length;++e)this.packValue(t[e])}packVec3(t){this.pack(t.x,t.y,t.z)}packColor(t){this.pack(t.r,t.g,t.b,t.a)}}const Wk=new Set;class Xk{constructor(){this.states={},this.serializer=new Gk(t=>{this.activeValues.push(t)});for(let t=0;t<ik.length;++t)this.states[ik[t]]={elements:new Map,valueStart:[],valueCount:[],values:[]}}reset(){ik.forEach(t=>{const e=this.states[t];e.elements.clear(),e.valueStart.length=0,e.valueCount.length=0,e.values.length=0})}pack(t){const e=this.states[t.type],i=e.values.length;this.activeValues=e.values,t.serialize(this.serializer),e.elements.set(t,e.elements.size),e.valueStart.push(i),e.valueCount.push(e.values.length-i)}compare(t){function e(t,e){for(const i of t.keys())if(!e.has(i))return!0}function i(t,e){for(const i of t)if(e(i))return!0;return!1}const s={added:new Array,removed:new Array,moved:new Array,changed:new Array};return ik.forEach(n=>{const r=t.states[n],a=this.states[n],o=r.elements,l=a.elements;!function(t,e,i){t.clear();for(const s of e.keys())i.has(s)&&t.add(s)}(Wk,o,l),e(l,Wk)&&s.added.push(n),e(o,Wk)&&s.removed.push(n),i(Wk.values(),t=>o.get(t)!==l.get(t))&&s.moved.push(n),i(Wk.values(),t=>{const e=o.get(t),i=l.get(t),s=r.valueCount[e];if(s!==a.valueCount[i])return!0;const n=r.valueStart[e],h=a.valueStart[i],c=r.values,d=a.values;for(let t=0;t<s;++t)if(c[n+t]!==d[h+t])return!0;return!1})&&s.changed.push(n)}),s}}class Yk extends nk{constructor(){super(ek.debug)}add(){const t=this.scene.graphicsDevice,e=new Sp({uniqueName:"splatOverlayMaterial",attributes:{vertex_id:ce},vertexGLSL:"\n attribute uint vertex_id;\n\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n\n uniform sampler2D splatState;\n uniform highp usampler2D splatPosition;\n uniform highp usampler2D splatTransform; // per-splat index into transform palette\n uniform sampler2D transformPalette; // palette of transform matrices\n\n uniform uvec2 texParams;\n\n uniform float splatSize;\n uniform vec4 selectedClr;\n uniform vec4 unselectedClr;\n\n varying vec4 varying_color;\n\n // calculate the current splat index and uv\n ivec2 calcSplatUV(uint index, uint width) {\n return ivec2(int(index % width), int(index / width));\n }\n\n void main(void) {\n ivec2 splatUV = calcSplatUV(vertex_id, texParams.x);\n uint splatState = uint(texelFetch(splatState, splatUV, 0).r * 255.0);\n\n if ((splatState & 6u) != 0u) {\n // deleted or locked (4 or 2)\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n gl_PointSize = 0.0;\n } else {\n mat4 model = matrix_model;\n \n // handle per-splat transform\n uint transformIndex = texelFetch(splatTransform, splatUV, 0).r;\n if (transformIndex > 0u) {\n // read transform matrix\n int u = int(transformIndex % 512u) * 3;\n int v = int(transformIndex / 512u);\n\n mat4 t;\n t[0] = texelFetch(transformPalette, ivec2(u, v), 0);\n t[1] = texelFetch(transformPalette, ivec2(u + 1, v), 0);\n t[2] = texelFetch(transformPalette, ivec2(u + 2, v), 0);\n t[3] = vec4(0.0, 0.0, 0.0, 1.0);\n\n model = matrix_model * transpose(t);\n }\n\n varying_color = (splatState == 1u) ? selectedClr : unselectedClr;\n\n vec3 center = uintBitsToFloat(texelFetch(splatPosition, splatUV, 0).xyz);\n\n gl_Position = matrix_viewProjection * model * vec4(center, 1.0);\n gl_PointSize = splatSize;\n }\n }\n",fragmentGLSL:"\n varying vec4 varying_color;\n\n void main(void) {\n gl_FragColor = varying_color;\n }\n"});e.blendType=2;const i=new gh(t),s=new Rh(i,e,null),n=this.scene.events,r=n=>{if(!n)return void(s.node=null);const r=n.splatData,a=new ms(t,[{semantic:ce,components:1,type:5,asInt:!0}]),o=new Uint32Array(r.numSplats);for(let t=0;t<r.numSplats;++t)o[t]=t;const l=new hs(t,a,r.numSplats,{usage:0,data:o.buffer});i.vertexBuffer&&(i.vertexBuffer.destroy(),i.vertexBuffer=null),i.vertexBuffer=l,i.primitive[0]={type:0,base:0,baseVertex:0,count:r.numSplats},e.setParameter("splatState",n.stateTexture),e.setParameter("splatPosition",n.entity.gsplat.instance.resource.transformATexture),e.setParameter("splatTransform",n.transformTexture),e.setParameter("texParams",[n.stateTexture.width,n.stateTexture.height]),e.update(),s.node=n.entity,this.splat=n};n.on("selection.changed",t=>{r(t)}),this.meshInstance=s}destroy(){this.meshInstance.material.destroy(),this.meshInstance.destroy()}onPreRender(){const t=this.scene.events,e=t.invoke("camera.splatSize");if(this.meshInstance.node&&this.scene.camera.renderOverlays&&e>0&&t.invoke("camera.overlay")&&"centers"===t.invoke("camera.mode")){const i=t.invoke("selectedClr"),s=t.invoke("unselectedClr"),{material:n}=this.meshInstance;n.setParameter("splatSize",e*window.devicePixelRatio),n.setParameter("selectedClr",[i.r,i.g,i.b,i.a]),n.setParameter("unselectedClr",[s.r,s.g,s.b,s.a]),n.setParameter("transformPalette",this.splat.transformPalette.texture),this.scene.app.drawMeshInstance(this.meshInstance)}}}class qk extends nk{constructor(){super(ek.other),this.enabled=!0,this.entity=new z_("underlayCamera"),this.entity.addComponent("camera"),this.entity.camera.setShaderPass("UNDERLAY"),this.entity.camera.clearColor=new H(0,0,0,0)}add(){const t=this.scene.app.graphicsDevice;this.entity.camera.layers=[this.scene.overlayLayer.id],this.scene.camera.entity.addChild(this.entity),this.shader=th.createShader(t,{uniqueName:"apply-underlay",attributes:{vertex_position:ce},vertexGLSL:"\n attribute vec2 vertex_position;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.0, 1.0);\n }\n",fragmentGLSL:"\n uniform sampler2D blitTexture;\n void main(void) {\n ivec2 texel = ivec2(gl_FragCoord.xy);\n\n gl_FragColor = texelFetch(blitTexture, texel, 0);\n }\n"}),this.quadRender=new rh(this.shader);const e=t.scope.resolve("blitTexture"),i=new Ji(!0,0,1,1,0,0,1);this.entity.camera.on("postRenderLayer",(s,n)=>{if(!this.entity.enabled||s!==this.scene.overlayLayer||!n)return;t.setBlendState(i),e.setValue(this.entity.camera.renderTarget.colorBuffer);const r=t;r.setRenderTarget(this.scene.camera.entity.camera.renderTarget),r.updateBegin(),this.quadRender.render(),r.updateEnd()})}remove(){this.scene.camera.entity.removeChild(this.entity)}onPreRender(){const t=this.scene.camera.entity.camera,e=this.entity.camera;e.projection=t.projection,e.horizontalFov=t.horizontalFov,e.fov=t.fov,e.nearClip=t.nearClip,e.farClip=t.farClip,e.orthoHeight=t.orthoHeight,this.entity.enabled=this.enabled&&!this.scene.events.invoke("view.outlineSelection"),this.entity.camera.renderTarget=this.scene.camera.workRenderTarget}}class jk{constructor(t,e,i,s){this.sceneState=[new Xk,new Xk],this.elements=[],this.boundStorage=new ut,this.boundDirty=!0,this.forceRender=!1,this.lockedRenderMode=!1,this.lockedRender=!1,this.canvasResize=null,this.targetSize={width:0,height:0},this.events=t,this.config=e,this.canvas=i,this.app=new Hk(i,{graphicsDevice:s}),this.app.autoRender=!1,this.app._allowResize=!1,this.app.scene.clusteredLightingEnabled=!1,this.app.off("prerender",this.app._firstBake,this.app),this.app.loader.getHandler("texture").imgParser.crossOrigin="anonymous",this.app.graphicsDevice.maxPixelRatio=window.devicePixelRatio;const n=new ResizeObserver(t=>{if(t.length>0){const e=t[0];if(e)if(e.devicePixelContentBoxSize)this.canvasResize={width:e.devicePixelContentBoxSize[0].inlineSize,height:e.devicePixelContentBoxSize[0].blockSize};else if(e.contentBoxSize.length>0){const t=window.devicePixelRatio;this.canvasResize={width:Math.ceil(e.contentBoxSize[0].inlineSize*t),height:Math.ceil(e.contentBoxSize[0].blockSize*t)}}this.forceRender=!0}}),r=window.document.getElementById("canvas-container")??this.canvas;r&&n.observe(r);const a=this.app.scene.layers.getLayerById(1);this.app.scene.layers.remove(a),this.app.scene.layers.insertOpaque(a,2),this.app.on("update",t=>this.onUpdate(t)),this.app.on("prerender",()=>this.onPreRender()),this.app.on("postrender",()=>this.onPostRender()),this.app.graphicsDevice.on("devicerestored",()=>{this.forceRender=!0}),this.app.scene.on(Ul,(t,e,i)=>{t.fire("preRenderLayer",e,i)}),this.app.scene.on(Bl,(t,e,i)=>{t.fire("postRenderLayer",e,i)}),this.backgroundLayer=new iu({enabled:!0,name:"Background Layer",opaqueSortMode:0,transparentSortMode:0}),this.shadowLayer=new iu({name:"Shadow Layer"}),this.debugLayer=new iu({enabled:!0,name:"Debug Layer",opaqueSortMode:0,transparentSortMode:0}),this.overlayLayer=new iu({name:"Overlay",clearDepthBuffer:!1,opaqueSortMode:0,transparentSortMode:0}),this.gizmoLayer=new iu({name:"Gizmo",clearDepthBuffer:!0,opaqueSortMode:0,transparentSortMode:0});const o=this.app.scene.layers,l=o.getLayerByName("World"),h=o.getOpaqueIndex(l);o.insert(this.backgroundLayer,h),o.insert(this.shadowLayer,h+1),o.insert(this.debugLayer,h+1),o.push(this.overlayLayer),o.push(this.gizmoLayer),this.dataProcessor=new Sk(this.app.graphicsDevice),this.assetLoader=new _k(this.app,t,this.app.graphicsDevice.maxAnisotropy),this.contentRoot=new z_("contentRoot"),this.app.root.addChild(this.contentRoot),this.cameraRoot=new z_("cameraRoot"),this.app.root.addChild(this.cameraRoot),this.camera=new zk,this.add(this.camera),this.splatOverlay=new Yk,this.add(this.splatOverlay),this.grid=new kk,this.add(this.grid),this.outline=new Vk,this.add(this.outline),this.underlay=new qk,this.add(this.underlay)}start(){this.app.start()}clear(){this.getElementsByType(ek.splat).forEach(t=>{this.remove(t),t.destroy()})}add(t){t.scene||(t.scene=this,t.add(),this.elements.push(t),this.forEachElement(e=>e!==t&&e.onAdded(t)),this.events.fire("scene.elementAdded",t))}remove(t){t.scene===this&&(this.elements.splice(this.elements.indexOf(t),1),this.events.fire("scene.elementRemoved",t),this.forEachElement(e=>e.onRemoved(t)),t.remove(),t.scene=null)}get bound(){if(this.boundDirty){let t=!1;this.forEachElement(e=>{const i=e.worldBound;i&&(t?this.boundStorage.add(i):(t=!0,this.boundStorage.copy(i)))}),this.boundDirty=!1,this.events.fire("scene.boundChanged",this.boundStorage)}return this.boundStorage}getElementsByType(t){return this.elements.filter(e=>e.type===t)}get graphicsDevice(){return this.app.graphicsDevice}forEachElement(t){this.elements.forEach(t)}onUpdate(t){this.forEachElement(e=>e.onUpdate(t)),this.events.fire("update",t);const e=this.app.frame%2,i=this.sceneState[e];i.reset(),this.forEachElement(t=>i.pack(t));const s=i.compare(this.sceneState[1-e]),n=new Set([...s.added,...s.removed,...s.moved,...s.changed]);this.lockedRenderMode?(this.app.renderNextFrame=this.lockedRender,this.lockedRender=!1):this.app.renderNextFrame||(this.app.renderNextFrame=this.forceRender||n.size>0),this.forceRender=!1,ik.forEach(t=>{n.has(t)&&this.events.fire(`updated:${t}`)}),this.forEachElement(t=>t.onPostUpdate())}onPreRender(){this.canvasResize&&(this.canvas.width=this.canvasResize.width,this.canvas.height=this.canvasResize.height,this.canvasResize=null),this.targetSize.width=Math.ceil(this.app.graphicsDevice.width/this.config.camera.pixelScale),this.targetSize.height=Math.ceil(this.app.graphicsDevice.height/this.config.camera.pixelScale),this.forEachElement(t=>t.onPreRender()),this.events.fire("prerender",this.camera.entity.getWorldTransform()),this.config.debug.showBound&&(this.forEachElement(t=>{if(t.type===ek.splat){const e=t,i=e.localBound;this.app.drawWireAlignedBox(i.getMin(),i.getMax(),H.RED,!0,void 0,e.entity.getWorldTransform());const s=e.worldBound;this.app.drawWireAlignedBox(s.getMin(),s.getMax(),H.GREEN)}}),this.app.drawWireAlignedBox(this.bound.getMin(),this.bound.getMax(),H.BLUE))}onPostRender(){this.forEachElement(t=>t.onPostRender()),this.events.fire("postrender")}}const $k={bgClr:{r:0,g:0,b:0,a:1},selectedClr:{r:1,g:1,b:0,a:1},unselectedClr:{r:0,g:0,b:1,a:.5},lockedClr:{r:0,g:0,b:0,a:.05},camera:{pixelScale:1,multisample:!1,fov:65,exposure:1,toneMapping:"linear",debugRender:"",overlay:!0,highPrecision:!0},show:{grid:!0,bound:!0,shBands:3},controls:{dampingFactor:.2,minPolarAngle:0,maxPolarAngle:Math.PI,minZoom:1e-6,maxZoom:10,initialAzim:-45,initialElev:-10,initialZoom:1,orbitSensitivity:.3,zoomSensitivity:.4},debug:{showBound:!1}};class Kk{constructor(t){this.sources=t}resolve(t,e){const i=t=>{for(const i of e){if(!t.hasOwnProperty(i))return;t=t[i]}return t};for(const e of t){const t=i(e);if(void 0!==t)return t}}get(t){return this.resolve(this.sources,t.split(".").map(t=>t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(t,e)=>(e?"-":"")+t.toLowerCase())))??this.resolve(this.sources,t.split("."))}getBool(t){const e=this.get(t);return"string"==typeof e?"true"===e.toLowerCase():void 0===e?void 0:!!e}getNumber(t){const e=this.get(t);return"string"==typeof e?parseFloat(e):e}getVec(t){const e=this.get(t);return"string"==typeof e?e.split(","):void 0}getVec3(t){const e=this.getVec(t);if(e){const t=e.map(t=>parseFloat(t));if(1===e.length)return{x:t[0],y:t[0],z:t[0]};if(3===e.length)return{x:t[0],y:t[1],z:t[2]}}}getColor(t){const e=this.getVec(t);if(e){const t=e.map(t=>parseFloat(t));if(1===e.length)return{r:t[0],g:t[0],b:t[0],a:1};if(3===e.length)return{r:t[0],g:t[1],b:t[2],a:1};if(4===e.length)return{r:t[0],g:t[1],b:t[2],a:t[3]}}}}const Zk=t=>{const e=new Kk(t),i=(t,e)=>t.length===e.length&&t.every((t,i)=>t===e[i]),s=(t,n)=>{for(const r in t){const a=`${n}${n.length?".":""}${r}`,o=t[r];switch(typeof o){case"number":t[r]=e.getNumber(a)??o;break;case"boolean":t[r]=e.getBool(a)??o;break;case"string":t[r]=e.get(a)??o;break;case"object":{const n=Object.keys(o).sort();i(n,["a","b","g","r"])?t[r]=e.getColor(a)??o:i(n,["x","y","z"])?t[r]=e.getVec3(a)??o:s(o,a);break}default:s(o,a)}}};return s($k,""),$k};class Qk{constructor(t){this._selectedIndices=new Set,this._selectionMask=null,this._maskTotalSplats=0,this._maskDirty=!1,this._selectionTexture=null,this._graphicsDevice=null,this._cachedSplatData=null,this._cachedEntity=null,this._onEvent=null,this._highlightColor={r:1,g:.5,b:0,a:1},this._onEvent=t||null}setGraphicsDevice(t){this._graphicsDevice=t}initializeSelectionMask(t){t<=0||(this._selectionMask&&this._maskTotalSplats===t||(this._selectionMask=new Uint8Array(t),this._maskTotalSplats=t,this._maskDirty=!0),this._selectionMask.fill(0),this._selectedIndices.clear(),this._maskDirty=!0)}getSelectionMask(){return this._selectionMask}getSelectionMaskInfo(){if(!this._selectionMask)return null;const t=this._maskTotalSplats,e=Math.min(t,4096),i=Math.ceil(t/4096);return{mask:this._selectionMask,totalSplats:t,selectedCount:this._selectedIndices.size,isDirty:this._maskDirty,textureWidth:e,textureHeight:i}}syncMaskFromIndices(){if(this._selectionMask){this._selectionMask.fill(0);for(const t of this._selectedIndices)t>=0&&t<this._maskTotalSplats&&(this._selectionMask[t]=1);this._maskDirty=!0}}getOrCreateSelectionTexture(){if(!this._graphicsDevice||!this._selectionMask)return null;const t=this.getSelectionMaskInfo();if(!t)return null;if(!this._selectionTexture||this._maskDirty){this._selectionTexture&&this._selectionTexture.destroy();const e=t.textureWidth,i=Math.max(1,t.textureHeight),s=new Uint8Array(e*i);s.set(this._selectionMask.subarray(0,Math.min(this._selectionMask.length,e*i)));for(let t=0;t<s.length;t++)s[t]=s[t]?255:0;this._selectionTexture=new Gi(this._graphicsDevice,{name:"splat-selection-mask",width:e,height:i,format:Jt,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});this._selectionTexture.lock().set(s),this._selectionTexture.unlock(),this._maskDirty=!1}return this._selectionTexture}updateSelectionTexture(){if(!this._selectionTexture||!this._selectionMask||!this._maskDirty)return;const t=this._selectionTexture.width,e=this._selectionTexture.height,i=new Uint8Array(t*e),s=Math.min(this._selectionMask.length,t*e);for(let t=0;t<s;t++)i[t]=this._selectionMask[t]?255:0;this._selectionTexture.lock().set(i),this._selectionTexture.unlock(),this._maskDirty=!1}setHighlightColor(t,e,i,s=1){this._highlightColor={r:Math.max(0,Math.min(1,t)),g:Math.max(0,Math.min(1,e)),b:Math.max(0,Math.min(1,i)),a:Math.max(0,Math.min(1,s))},this._emitEvent("splat-highlight-color-changed",this._highlightColor)}getHighlightColor(){return{...this._highlightColor}}extractSplatData(t){const e={numSplats:0,x:null,y:null,z:null,hasPositions:!1};if(!t)return e;const i=t.gsplat;if(!i)return e;let s=null,n=null;i.instance?.resource?.gsplatData?(s=i.instance.resource.gsplatData,n=i.instance.resource):i.asset?.resource?.gsplatData?(s=i.asset.resource.gsplatData,n=i.asset.resource):i.instance?.gsplatData?s=i.instance.gsplatData:i.instance?.resource?.splatData&&(s=i.instance.resource.splatData,n=i.instance.resource),s?e.numSplats=s.numSplats||s.meta?.count||s.count||0:n?e.numSplats=n.numSplats||0:"number"==typeof i.numSplats?e.numSplats=i.numSplats:"number"==typeof i.splatCount&&(e.numSplats=i.splatCount);const r=(t,i)=>{e.x=new Float32Array(i),e.y=new Float32Array(i),e.z=new Float32Array(i);for(let s=0;s<i;s++)e.x[s]=t[3*s],e.y[s]=t[3*s+1],e.z[s]=t[3*s+2];e.numSplats=i,e.hasPositions=!0};if(s)if(s.x instanceof Float32Array)e.x=s.x,e.y=s.y,e.z=s.z,e.hasPositions=!0;else if(s.centers instanceof Float32Array){const t=s.centers;r(t,e.numSplats||t.length/3)}else if(s._centers instanceof Float32Array){const t=s._centers;r(t,e.numSplats||t.length/3)}else if(s.positions instanceof Float32Array){const t=s.positions;r(t,e.numSplats||t.length/3)}else if(s.means instanceof Float32Array){const t=s.means;r(t,e.numSplats||t.length/3)}if(!e.hasPositions&&n)if(n.centers instanceof Float32Array){const t=n.centers;r(t,e.numSplats||t.length/3)}else if(n._centers instanceof Float32Array){const t=n._centers;r(t,e.numSplats||t.length/3)}if(!e.hasPositions&&i.instance){const t=i.instance;if(t.centers instanceof Float32Array){const i=t.centers;r(i,e.numSplats||i.length/3)}else if("function"==typeof t.getCenters)try{const i=t.getCenters();if(i instanceof Float32Array){r(i,e.numSplats||i.length/3)}}catch(t){}}return this._cachedSplatData=e,this._cachedEntity=t,e.numSplats>0&&(!this._selectionMask||this._maskTotalSplats!==e.numSplats)&&this.initializeSelectionMask(e.numSplats),e}getDebugInfo(t){const e={hasGSplat:!1,hasPositionData:!1,positionDataFormat:null,centersLocation:null,numSplats:0};if(!t||!t.gsplat)return e;e.hasGSplat=!0;const i=t.gsplat,s=i.instance?.resource?.gsplatData||i.asset?.resource?.gsplatData||i.instance?.gsplatData||i.instance?.resource?.splatData||null,n=i.instance?.resource||i.asset?.resource||i.instance?.resource||null;return s&&(s.x instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.xyz",e.centersLocation="gsplatData.x/y/z",e.numSplats=s.x.length):s.centers instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.centers",e.centersLocation="gsplatData.centers",e.numSplats=s.centers.length/3):s._centers instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData._centers",e.centersLocation="gsplatData._centers",e.numSplats=s._centers.length/3):s.positions instanceof Float32Array?(e.hasPositionData=!0,e.positionDataFormat="gsplatData.positions",e.centersLocation="gsplatData.positions",e.numSplats=s.positions.length/3):s.means instanceof Float32Array&&(e.hasPositionData=!0,e.positionDataFormat="gsplatData.means",e.centersLocation="gsplatData.means",e.numSplats=s.means.length/3),!e.numSplats&&s.numSplats&&(e.numSplats=s.numSplats),!e.numSplats&&s.meta?.count&&(e.numSplats=s.meta.count)),!e.numSplats&&n?.numSplats&&(e.numSplats=n.numSplats),!e.hasPositionData&&i.instance?.centers instanceof Float32Array&&(e.hasPositionData=!0,e.positionDataFormat="instance.centers",e.centersLocation="instance.centers",e.numSplats=i.instance.centers.length/3),e}selectSplatsInBox(t,e,i=!1){let s=this._cachedSplatData;s&&this._cachedEntity===t||(s=this.extractSplatData(t)),this._selectionMask&&this._maskTotalSplats===s.numSplats||this.initializeSelectionMask(s.numSplats);const n={indices:new Uint32Array(0),count:0,totalSplats:s.numSplats,mask:this._selectionMask||new Uint8Array(0)};if(!(s.hasPositions&&s.x&&s.y&&s.z))return this._emitEvent("splat-selection-error",{message:"No position data available",code:"NO_POSITION_DATA"}),n;i||(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));const{x:r,y:a,z:o}=s,l=[];let h=null,c=!1;t&&t.getWorldTransform&&(h=t.getWorldTransform(),c=!0);for(let t=0;t<s.numSplats;t++){let i=r[t],s=a[t],n=o[t];if(c&&h){const e=h.data,l=r[t],c=a[t],d=o[t];i=e[0]*l+e[4]*c+e[8]*d+e[12],s=e[1]*l+e[5]*c+e[9]*d+e[13],n=e[2]*l+e[6]*c+e[10]*d+e[14]}i>=e.minX&&i<=e.maxX&&s>=e.minY&&s<=e.maxY&&n>=e.minZ&&n<=e.maxZ&&(this._selectedIndices.add(t),l.push(t),this._selectionMask&&(this._selectionMask[t]=1))}return this._maskDirty=!0,n.indices=new Uint32Array(this._selectedIndices),n.count=this._selectedIndices.size,n.mask=this._selectionMask||new Uint8Array(0),this._emitEvent("splat-selection-changed",{selectedCount:n.count,totalSplats:n.totalSplats,newlySelected:l.length,hasMask:!!this._selectionMask}),n}selectSplatsInSphere(t,e,i=!1){let s=this._cachedSplatData;s&&this._cachedEntity===t||(s=this.extractSplatData(t)),this._selectionMask&&this._maskTotalSplats===s.numSplats||this.initializeSelectionMask(s.numSplats);const n={indices:new Uint32Array(0),count:0,totalSplats:s.numSplats,mask:this._selectionMask||new Uint8Array(0)};if(!(s.hasPositions&&s.x&&s.y&&s.z))return this._emitEvent("splat-selection-error",{message:"No position data available",code:"NO_POSITION_DATA"}),n;i||(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));const{x:r,y:a,z:o}=s,l=[],h=e.radius*e.radius;let c=null,d=!1;t&&t.getWorldTransform&&(c=t.getWorldTransform(),d=!0);for(let t=0;t<s.numSplats;t++){let i=r[t],s=a[t],n=o[t];if(d&&c){const e=c.data,l=r[t],h=a[t],d=o[t];i=e[0]*l+e[4]*h+e[8]*d+e[12],s=e[1]*l+e[5]*h+e[9]*d+e[13],n=e[2]*l+e[6]*h+e[10]*d+e[14]}const u=i-e.cx,p=s-e.cy,f=n-e.cz;u*u+p*p+f*f<=h&&(this._selectedIndices.add(t),l.push(t),this._selectionMask&&(this._selectionMask[t]=1))}return this._maskDirty=!0,n.indices=new Uint32Array(this._selectedIndices),n.count=this._selectedIndices.size,n.mask=this._selectionMask||new Uint8Array(0),this._emitEvent("splat-selection-changed",{selectedCount:n.count,totalSplats:n.totalSplats,newlySelected:l.length,hasMask:!!this._selectionMask}),n}createBoxFromProperties(t,e){const i=e.x/2,s=e.y/2,n=e.z/2;return{minX:t.x-i,maxX:t.x+i,minY:t.y-s,maxY:t.y+s,minZ:t.z-n,maxZ:t.z+n}}getSelectedIndices(){return new Uint32Array(this._selectedIndices)}getSelectionCount(){return this._selectedIndices.size}clearSelection(){const t=this._selectedIndices.size;this._selectedIndices.clear(),this._selectionMask&&(this._selectionMask.fill(0),this._maskDirty=!0),this._emitEvent("splat-selection-cleared",{previousCount:t})}isSplatSelected(t){return this._selectedIndices.has(t)}addToSelection(t){for(const e of t)this._selectedIndices.add(e),this._selectionMask&&e>=0&&e<this._maskTotalSplats&&(this._selectionMask[e]=1);this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,added:t.length})}removeFromSelection(t){for(const e of t)this._selectedIndices.delete(e),this._selectionMask&&e>=0&&e<this._maskTotalSplats&&(this._selectionMask[e]=0);this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,removed:t.length})}invertSelection(t){this._selectionMask&&this._maskTotalSplats===t||this.initializeSelectionMask(t);const e=new Set;for(let i=0;i<t;i++)this._selectedIndices.has(i)?this._selectionMask&&(this._selectionMask[i]=0):(e.add(i),this._selectionMask&&(this._selectionMask[i]=1));this._selectedIndices=e,this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,inverted:!0})}selectByIndices(t,e=!0){e&&(this._selectedIndices.clear(),this._selectionMask&&this._selectionMask.fill(0));for(const e of t)e>=0&&e<this._maskTotalSplats&&(this._selectedIndices.add(e),this._selectionMask&&(this._selectionMask[e]=1));this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,setDirectly:t.length})}selectAll(){if(!(this._maskTotalSplats<=0)){this._selectedIndices.clear();for(let t=0;t<this._maskTotalSplats;t++)this._selectedIndices.add(t);this._selectionMask&&this._selectionMask.fill(1),this._maskDirty=!0,this._emitEvent("splat-selection-changed",{selectedCount:this._selectedIndices.size,selectedAll:!0})}}clearCache(){this._cachedSplatData=null,this._cachedEntity=null}isMaskDirty(){return this._maskDirty}markMaskClean(){this._maskDirty=!1}getMaskTotalSplats(){return this._maskTotalSplats}destroy(){this._selectedIndices.clear(),this._cachedSplatData=null,this._cachedEntity=null,this._onEvent=null,this._selectionMask=null,this._maskTotalSplats=0,this._maskDirty=!1,this._selectionTexture&&(this._selectionTexture.destroy(),this._selectionTexture=null),this._graphicsDevice=null}_emitEvent(t,e){this._onEvent&&this._onEvent(t,e)}}class Jk{constructor(t,e,i){this.device=null,this.events=null,this.scene=null,this.assetLoader=null,this.models=new Map,this.nextModelId=0,this.activeModelId=null,this.pendingGridEnabled=null,this.dataProcessor=null,this.navigationCube=null,this.navigationCubeConfig=null,this.emitEvent=null,this.viewerEventState={cameraMode:"centers",cameraOverlay:!0,cameraHighPrecision:!0,cameraBound:!0,cameraSplatSize:1,viewOutlineSelection:!1,viewBands:3},this.blobUrl=null,this.canvas=t,this.selectionMgr=new Qk,this.navigationCubeConfig=e||null,this.emitEvent=i||null}get currentSplat(){if(this.activeModelId){const t=this.models.get(this.activeModelId);if(t?.splat)return t.splat}const t=this.models.values().next().value;return t?.splat??null}getEntityTransform(t){const e=t.getLocalPosition(),i=t.getLocalRotation(),s=t.getLocalScale(),n=i.getEulerAngles(),r=t.getLocalTransform().data,a=[r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15]];return{position:{x:e.x,y:e.y,z:e.z},rotation:{x:n.x,y:n.y,z:n.z},scale:{x:s.x,y:s.y,z:s.z},matrix:a}}calculateBoundingBox(t){const e=new ut;if("function"==typeof t.getWorldTransform&&t.getWorldTransform(),"function"==typeof t._calculateHierarchyBounds)t._calculateHierarchyBounds(e);else if(t.gsplat?.bounds){const i=t.gsplat.bounds;e.center.set(i.center.x,i.center.y,i.center.z),e.halfExtents.set(i.halfExtents.x,i.halfExtents.y,i.halfExtents.z)}const i={x:e.center.x,y:e.center.y,z:e.center.z},s={x:e.halfExtents.x,y:e.halfExtents.y,z:e.halfExtents.z};return{center:i,halfExtents:s,min:{x:i.x-s.x,y:i.y-s.y,z:i.z-s.z},max:{x:i.x+s.x,y:i.y+s.y,z:i.z+s.z}}}getFileMeta(t){if("string"==typeof t){const e=(t.split("/").pop()||"").split("?")[0]||void 0,i=e?.split(".").pop()?.toLowerCase();return{fileSize:0,fileType:i||"unknown",fileName:e}}if(t instanceof File){const e=t.name.split(".").pop()?.toLowerCase();return{fileSize:t.size,fileType:e||"unknown",fileName:t.name}}return{fileSize:t.size,fileType:"blob"}}createPseudoAsset(t){return{name:t,type:"supersplat",loaded:!0,resource:null,unload:()=>{},destroy:()=>{}}}async init(){let t=await aa(this.canvas,{deviceTypes:["webgl2"],antialias:!1,depth:!1,stencil:!1,xrCompatible:!1,powerPreference:"high-performance"});if(t&&"object"==typeof t&&(t.graphicsDevice?t=t.graphicsDevice:t.device&&(t=t.device)),!t||!t.canvas)throw new Error("SupersplatAdapter: Failed to create graphics device");this.events=new xk;const e=Zk([{}]);if(this.scene=new jk(this.events,e,this.canvas,t),!this.scene?.app?.graphicsDevice)throw new Error("SupersplatAdapter: PlayCanvas app failed to initialize graphicsDevice");this.registerViewerEventDefaults(),this.assetLoader=new _k(this.scene.app,this.events,this.scene.app.graphicsDevice.maxAnisotropy),this.dataProcessor=new Sk(this.scene.app.graphicsDevice),this.scene.app.autoRender=!0,this.scene.start(),null!==this.pendingGridEnabled&&(this.scene.grid.visible=this.pendingGridEnabled,this.scene.forceRender=!0,this.pendingGridEnabled=null),this.setHighlightColor(1,.5,0,.8),this.initializeNavigationCube()}initializeNavigationCube(){if(this.navigationCubeConfig&&this.navigationCubeConfig.enabled&&this.scene&&this.scene.app&&this.scene.camera)try{this.navigationCube=new Pz(this.navigationCubeConfig);const t=this.createCameraAdapter();this.navigationCube.initialize(this.scene.app,this.scene.camera.entity,t,this.emitEvent||void 0),this.scene.app.on("update",this.updateNavigationCube.bind(this))}catch(t){this.navigationCube=null}}createCameraAdapter(){if(!this.scene||!this.scene.camera)throw new Error("SupersplatAdapter: Scene camera not available");const t=this.scene.camera;return{get pitch(){return t.elevation},get yaw(){return t.azim},get distance(){return t.distance},get target(){return t.focalPoint},updateCameraPosition:()=>{},setTargetPitch:(e,i)=>{const s=i?1:0;t.setAzimElev(t.azim,e,s)},setTargetYaw:(e,i)=>{const s=i?1:0;t.setAzimElev(e,t.elevation,s)},setAzimElev:(e,i,s)=>{const n=s?1:0;t.setAzimElev(e,i,n)}}}updateNavigationCube(t){this.navigationCube&&this.scene?.camera&&(this.navigationCube.update(t),this.navigationCube.syncWithCamera(this.scene.camera.elevation,this.scene.camera.azim))}async load(t){if(!this.scene||!this.assetLoader)throw new Error("SupersplatAdapter: init() must be called before load()");t instanceof Blob&&this._cleanupBlobUrl();const e=this.toAssetSource(t),i=performance.now();try{const s=await this.assetLoader.load(e);this.clear(),this.scene.add(s);const n="model_"+this.nextModelId++,r=this.getFileName(t);this.activeModelId=n;const a=this.getEntityTransform(s.entity),{fileSize:o,fileType:l,fileName:h}=this.getFileMeta(t),c=this.calculateBoundingBox(s.entity),d=this.getSplatCount(s),u=64*d,p=performance.now()-i,f={name:r,id:n,fileSize:o,fileType:l,splatCount:d,boundingBox:c,transform:a,memoryUsage:u,loadedAt:Date.now(),loadDuration:p};void 0!==h&&(f.fileName=h);const m=this.createPseudoAsset(r);return this.models.set(n,{id:n,name:r,splat:s,asset:m,visible:!0,transform:a,metadata:f}),this.scene.forceRender=!0,this.clearSelection(),this.emitEvent?.("model-added",{modelId:n,info:{id:n,name:r,entity:s.entity,asset:m,transform:a,metadata:f}}),{splat:s}}catch(t){throw t}}async addModel(t,e={}){if(!this.scene||!this.assetLoader)throw new Error("SupersplatAdapter: init() must be called before addModel()");const i=this.toAssetSource(t),s=performance.now();try{const n=await this.assetLoader.load(i);this.scene.add(n);const r="model_"+this.nextModelId++,a=e.name||this.getFileName(t);this.activeModelId=r;const o=this.getEntityTransform(n.entity),{fileSize:l,fileType:h,fileName:c}=this.getFileMeta(t),d=this.calculateBoundingBox(n.entity),u=this.getSplatCount(n),p=64*u,f=performance.now()-s,m={name:a,id:r,fileSize:l,fileType:h,splatCount:u,boundingBox:d,transform:o,memoryUsage:p,loadedAt:Date.now(),loadDuration:f};void 0!==c&&(m.fileName=c);const _=this.createPseudoAsset(a),g={id:r,name:a,splat:n,asset:_,visible:!1!==e.visible,transform:o,metadata:m};return this.models.set(r,g),g.visible||(n.visible=!1),this.scene.forceRender=!0,this.emitEvent?.("model-added",{modelId:r,info:{id:r,name:a,entity:n.entity,asset:_,transform:g.transform,metadata:g.metadata}}),{id:r,name:a,entity:n.entity,asset:_,transform:g.transform,metadata:g.metadata,visible:g.visible}}catch(t){throw t}}getSelectedIndices(){return this.selectionMgr.getSelectedIndices()}removeModel(t){const e=this.models.get(t);return!!e&&(this.scene&&(this.scene.remove(e.splat),e.splat.destroy()),this.models.delete(t),this.activeModelId===t&&(this.activeModelId=null),this.scene&&(this.scene.forceRender=!0),this.emitEvent?.("model-removed",{modelId:t}),!0)}getModels(){const t=[];return this.models.forEach(e=>{t.push({id:e.id,name:e.name,entity:e.splat.entity,asset:e.asset,transform:e.transform,metadata:e.metadata,visible:e.visible})}),t}getModelById(t){const e=this.models.get(t);return e?{id:e.id,name:e.name,entity:e.splat.entity,asset:e.asset,transform:e.transform,metadata:e.metadata,visible:e.visible}:null}updateModelTransform(t,e){const i=this.models.get(t);if(!i)throw new Error(`SupersplatAdapter.updateModelTransform: Model not found: ${t}`);i.transform=e,i.metadata.transform=e,this.scene&&(this.scene.forceRender=!0)}setGridEnabled(t){this.scene?(this.scene.grid.visible=t,this.scene.forceRender=!0):this.pendingGridEnabled=t}isGridEnabled(){return this.scene?.grid?.visible??this.pendingGridEnabled??!0}setModelVisible(t,e){const i=this.models.get(t);return!!i&&(i.visible=e,i.splat.visible=e,this.scene&&(this.scene.forceRender=!0),!0)}setModelsVisibleByName(t,e){this.models.forEach(i=>{i.name===t&&(i.visible=e,i.splat.visible=e)}),this.scene&&(this.scene.forceRender=!0)}getModelStats(t){const e=this.models.get(t);if(!e)throw new Error(`Model not found: ${t}`);return e.metadata}getAllModelStats(){const t={};return this.models.forEach((e,i)=>{t[i]=e.metadata}),t}getSceneStats(){let t=0,e=0,i=0,s=1/0,n=1/0,r=1/0,a=-1/0,o=-1/0,l=-1/0;this.models.forEach(h=>{t+=h.metadata.splatCount,e+=h.metadata.fileSize,i+=h.metadata.memoryUsage;const c=h.metadata.boundingBox;s=Math.min(s,c.min.x),n=Math.min(n,c.min.y),r=Math.min(r,c.min.z),a=Math.max(a,c.max.x),o=Math.max(o,c.max.y),l=Math.max(l,c.max.z)});const h=this.models.size>0&&isFinite(s)&&isFinite(a),c=h?{x:(s+a)/2,y:(n+o)/2,z:(r+l)/2}:{x:0,y:0,z:0},d=h?{x:(a-s)/2,y:(o-n)/2,z:(l-r)/2}:{x:0,y:0,z:0};return{modelCount:this.models.size,totalSplats:t,totalFileSize:e,totalMemoryUsage:i,bounds:{center:c,halfExtents:d}}}getFileName(t){return"string"==typeof t?t.split("/").pop()||"model.splat":t instanceof File?t.name:"model.splat"}getSplatCount(t){try{const e=t.splatData;if(e&&"number"==typeof e.numSplats)return e.numSplats}catch{}return 0}clear(){this._cleanupBlobUrl(),this.models.forEach(t=>{t.splat.destroy()}),this.models.clear(),this.scene?.clear(),this.clearSelection(),this.scene&&(this.scene.forceRender=!0)}focus(){this.scene&&(this.scene.forceRender=!0)}onCanvasResize(){this.navigationCube&&"function"==typeof this.navigationCube.onCanvasResize&&this.navigationCube.onCanvasResize()}destroy(){this.navigationCube&&("function"==typeof this.navigationCube.cleanup&&this.navigationCube.cleanup(),this.navigationCube=null)}setHighlightColor(t,e,i,s=.8){if(!this.events)return;const n=new H(t,e,i,s);this.events.fire("setSelectedClr",n)}setCameraFOV(t){this.scene&&("number"!=typeof t||isNaN(t)||t<1||t>179||(this.scene.camera.fov=t,this.scene.forceRender=!0))}getCameraFOV(){return this.scene?.camera?.fov??60}selectInBox(t,e=!1){const i=this.currentSplat;if(!i||!this.scene)return null;const s=this.selectionMgr.selectSplatsInBox(i.entity,t,e);return this.applySelectionToSplat(i,s?.indices),this.scene.forceRender=!0,s}selectInSphere(t,e=!1){const i=this.currentSplat;if(!i||!this.scene)return null;const s=this.selectionMgr.selectSplatsInSphere(i.entity,t,e);return this.applySelectionToSplat(i,s?.indices),this.scene.forceRender=!0,s}clearSelection(){const t=this.currentSplat;if(!t)return;const e=t.splatData.getProp("state");if(e){for(let t=0;t<e.length;t++)e[t]=-2&e[t];t.updateState(),this.scene&&(this.scene.forceRender=!0)}}applySelectionToSplat(t,e){if(!e)return;const i=t.splatData.getProp("state");if(i)if(0!==e.length){for(let t=0;t<i.length;t++)i[t]=-2&i[t];for(let t=0;t<e.length;t++){const s=e[t];s>=0&&s<i.length&&(i[s]=1|i[s])}t.updateState()}else this.clearSelection()}toAssetSource(t){if("string"==typeof t)return{url:t};if(t instanceof File)return{filename:t.name,contents:t};const e=URL.createObjectURL(t);return this.blobUrl=e,{filename:"local.splat",url:e,contents:t}}_cleanupBlobUrl(){if(this.blobUrl){try{URL.revokeObjectURL(this.blobUrl)}catch{}this.blobUrl=null}}getPlayCanvasContext(){return this.scene?{app:this.scene.app,root:this.scene.app.root,camera:this.scene.camera?.entity??null}:null}setCameraControlsEnabled(t){const e=this.scene?.camera?.controller;if(e)try{"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t)}catch(t){}}setCameraInputControls(t){const e=this.scene?.camera?.controller;if(e)try{"function"==typeof e.setInputControls&&e.setInputControls(t)}catch(t){}}setCameraManualControl(t){const e=this.scene?.camera;if(e)try{"function"==typeof e.setManualControl?e.setManualControl(t):(e.manualControl=!!t,e.controller?.setEnabled?.(!t))}catch(t){}}syncOrbitFromCameraEntity(t=new K(0,0,0)){const e=this.scene?.camera,i=this.scene?.camera?.entity;if(e&&i)try{const s=i.getPosition?i.getPosition().clone():i.getLocalPosition().clone();"function"==typeof e.setPose&&e.setPose(s,t,0),this.scene&&(this.scene.forceRender=!0)}catch(t){}}registerViewerEventDefaults(){if(!this.events||!this.scene)return;const{config:t}=this.scene,e=this.viewerEventState,i=t.selectedClr??{r:1,g:.5,b:0,a:1},s=t.unselectedClr??{r:0,g:0,b:1,a:.5},n=t.lockedClr??{r:0,g:0,b:0,a:.05},r=t.bgClr??{r:0,g:0,b:0,a:1};e.cameraOverlay=t.camera?.overlay??e.cameraOverlay,e.cameraHighPrecision=t.camera?.highPrecision??e.cameraHighPrecision,e.cameraBound=t.show?.bound??e.cameraBound,e.viewBands=t.show?.shBands??e.viewBands,this.events.function("camera.mode",()=>e.cameraMode),this.events.on("camera.mode",t=>{e.cameraMode=t}),this.events.function("camera.overlay",()=>e.cameraOverlay),this.events.on("camera.overlay",t=>{e.cameraOverlay=!!t}),this.events.function("camera.highPrecision",()=>e.cameraHighPrecision),this.events.on("camera.highPrecision",t=>{e.cameraHighPrecision=!!t}),this.events.function("camera.bound",()=>e.cameraBound),this.events.on("camera.bound",t=>{e.cameraBound=!!t}),this.events.function("camera.splatSize",()=>e.cameraSplatSize),this.events.on("camera.splatSize",t=>{e.cameraSplatSize="number"==typeof t?t:e.cameraSplatSize}),this.events.function("view.outlineSelection",()=>e.viewOutlineSelection),this.events.on("view.outlineSelection",t=>{e.viewOutlineSelection=!!t}),this.events.function("view.bands",()=>e.viewBands),this.events.on("view.bands",t=>{e.viewBands="number"==typeof t?t:e.viewBands}),this.events.function("selectedClr",()=>i),this.events.function("unselectedClr",()=>s),this.events.function("lockedClr",()=>n),this.events.function("bgClr",()=>r),this.events.function("selection",()=>this.currentSplat)}}class tV{constructor(t){this._eventEmitter=t}applyTransformMatrix(t,e,i){const s=new rt;s.data.set(e);const{pos:n,rot:r,scale:a}=this.decomposeMatrix(s);t.setLocalPosition(n),t.setLocalRotation(r),t.setLocalScale(a);const o=this.getTransform(t);this.emitTransformEvent(i,o)}getTransformMatrix(t){const e=t.getLocalTransform().data;return[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]]}setPosition(t,e,i){t.setLocalPosition(e.x,e.y,e.z);const s=this.getTransform(t);this.emitTransformEvent(i,s)}setRotation(t,e,i){const s=this.eulerToQuat(e);t.setLocalRotation(s);const n=this.getTransform(t);this.emitTransformEvent(i,n)}setScale(t,e,i){t.setLocalScale(e.x,e.y,e.z);const s=this.getTransform(t);this.emitTransformEvent(i,s)}getTransform(t){const e=t.getLocalPosition(),i=t.getLocalRotation(),s=t.getLocalScale(),n=this.quatToEuler(i),r=this.getTransformMatrix(t);return{position:{x:e.x,y:e.y,z:e.z},rotation:n,scale:{x:s.x,y:s.y,z:s.z},matrix:r}}resetTransform(t,e){t.setLocalPosition(0,0,0),t.setLocalRotation(0,0,0,1),t.setLocalScale(1,1,1);const i=this.getTransform(t);this.emitTransformEvent(e,i)}decomposeMatrix(t){const e=new K,i=new at,s=new K;t.getTranslation(e);const n=t.data,r=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),a=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),o=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);s.set(r,a,o);const l=new rt;l.data[0]=n[0]/r,l.data[1]=n[1]/r,l.data[2]=n[2]/r,l.data[3]=0,l.data[4]=n[4]/a,l.data[5]=n[5]/a,l.data[6]=n[6]/a,l.data[7]=0,l.data[8]=n[8]/o,l.data[9]=n[9]/o,l.data[10]=n[10]/o,l.data[11]=0,l.data[12]=0,l.data[13]=0,l.data[14]=0,l.data[15]=1,l.getEulerAngles(i);const h=i;return i.setFromEulerAngles(h.x,h.y,h.z),{pos:e,rot:i,scale:s}}eulerToQuat(t){const e=new at;return e.setFromEulerAngles(t.x,t.y,t.z),e}quatToEuler(t){const e=new K;return t.getEulerAngles(e),{x:e.x,y:e.y,z:e.z}}emitTransformEvent(t,e){this._eventEmitter&&this._eventEmitter("model-transform-changed",{modelId:t,transform:e})}}var eV;!function(t){t.ORBIT="orbit",t.FLY="fly"}(eV||(eV={}));const iV={moveSpeed:5,fastSpeedMultiplier:3,slowSpeedMultiplier:.3,lookSensitivity:.2,invertY:!1,keyBindings:{forward:"KeyW",backward:"KeyS",left:"KeyA",right:"KeyD",up:"KeyE",down:"KeyQ",fastMove:"ShiftLeft",slowMove:"ControlLeft"},smoothing:.8,friction:.85,enableCollision:!1,minHeight:null,maxHeight:null};class SplatViewerCore{constructor(t={}){this.canvas=null,this.app=null,this.entities={camera:null,light:null,splat:null},this.enableStats=!1,this.autoFocus=!0,this.previewMode=!1,this.isLoading=!1,this.hasModel=!1,this.error=null,this._orbit=null,this._fly=null,this._cameraModeManager=null,this._cameraMode="orbit",this._statsHandler=null,this._asset=null,this._blobUrl=null,this._resizeObserver=null,this._resizeHandler=null,this.initialCameraPosition=null,this._navigationCubeConfig=null,this._modelManager=null,this._transformSystem=null,this._sceneConfigManager=null,this._skyboxEnabled=!1,this._skyboxLoadingPromise=null,this._eventListeners=new Map,this._splatCenterSize=null,this._sphericalHarmonicsBands=null,this._gridEnabled=!1,this._infiniteGrid=null,this._boxSelectionAPI=null,this._boxSelectionEnabled=!0,this._sphereSelectionAPI=null,this._sphereSelectionEnabled=!0,this._splatSelectionManager=null,this._splatHighlightShader=null,this._highlightEnabled=!0,this._splatHighlightOverlay=null,this._outlineEnabled=!1,this._supersplat=null,this._supersplatReady=null,this._supersplatBlobUrl=null,this._boundingBoxEnabled=!1,this._boundingBoxRenderHandler=null,this._selectedModelIdForBoundingBox=null,this.canvas=t.canvas||null,this.enableStats=t.enableStats||!1,this.autoFocus=!1!==t.autoFocus,this.previewMode=t.previewMode||!1,this.previewMode&&(this.autoFocus=!0),this._navigationCubeConfig=t.navigationCube||null,void 0!==t.onStatsUpdate&&(this._onStatsUpdate=t.onStatsUpdate),void 0!==t.onError&&(this._onError=t.onError),void 0!==t.onLoadingStart&&(this._onLoadingStart=t.onLoadingStart),void 0!==t.onLoaded&&(this._onLoaded=t.onLoaded)}async whenReady(){this._supersplatReady&&await this._supersplatReady}init(t){if(this.canvas=t||this.canvas,!this.canvas)throw new Error("SplatViewerCore.init: canvas is required");const e=(t,e)=>{this.emit({type:t,detail:e})};return this._supersplat=new Jk(this.canvas,this.previewMode?null:this._navigationCubeConfig,e),this._supersplatReady=this._supersplat.init(),this._supersplatReady?.then(()=>{this.previewMode&&this._supersplat&&this._supersplat.setCameraInputControls?.({orbit:!1,pan:!1,zoom:!0}),this.previewMode||this._setupFlyCameraForSupersplat()}).catch(t=>{}),this._transformSystem=new tV(e),this._gridEnabled=!0,this._supersplatReady?.then(()=>{this._supersplat&&(this._gridEnabled=this._supersplat.isGridEnabled())}).catch(t=>{}),this.app=null,this}_setupFlyCameraForSupersplat(){if(!this._supersplat)return;const t=this._supersplat.getPlayCanvasContext?.();if(!t?.app||!t?.camera)return;this.app=t.app,this.entities.camera=t.camera;const e=this.entities.camera;if(e&&!e.script&&"function"==typeof e.addComponent)try{e.addComponent("script")}catch{}try{iD();const i={moveSpeed:iV.moveSpeed,fastSpeedMultiplier:iV.fastSpeedMultiplier,slowSpeedMultiplier:iV.slowSpeedMultiplier,lookSensitivity:iV.lookSensitivity,invertY:iV.invertY,keyBindings:iV.keyBindings,smoothing:iV.smoothing,friction:iV.friction,enableCollision:iV.enableCollision,minHeight:iV.minHeight,maxHeight:iV.maxHeight};if("function"==typeof e?.script?.create){const t=e.script.create("flyCamera",{attributes:i});this._fly=t,this._fly&&(this._fly.emitFlyEvent=(t,e)=>{this.emit({type:t,detail:e})},this._fly.deactivate?.())}else{const s=new eD(t.app,e,(t,e)=>this.emit({type:t,detail:e}),i);s.deactivate(),this._fly=s}this._cameraMode="orbit"}catch(t){}}_resolveModelEntityForId(t,e){if(this._supersplat){const i=this._supersplat.getModelById(t);if(!i||!i.entity)throw new Error(`${e}: Model with ID "${t}" not found (SuperSplat path)`);return i.entity}if(!this._modelManager)throw new Error(`${e}: ModelManager not initialized`);const i=this._modelManager.getModelById(t);if(!i)throw new Error(`${e}: Model with ID "${t}" not found`);return i.entity}async load(t,e={}){if(this._supersplat){await this._supersplatReady,this.clear(),this.isLoading=!0,this.error=null,this._onLoadingStart?.(),this.emit({type:"loading-start",detail:{source:"string"==typeof t?t:"file/blob"}});try{const e=await this._supersplat.load(t);return this.entities.splat=e.splat.entity,this.hasModel=!0,this.isLoading=!1,this._onLoaded?.({entity:this.entities.splat,asset:null}),this.emit({type:"loaded",detail:{entity:this.entities.splat,asset:null}}),{entity:this.entities.splat,asset:null}}catch(t){throw this.error="UNKNOWN_LOADER_ERROR",this._onError?.(this.error),this.emit({type:"error",detail:{message:this.error,code:"UNKNOWN_ERROR"}}),t}}if(!this.app)throw new Error("SplatViewerCore.load: call init() first");this.clear(),this.isLoading=!0,this.error=null,this._onLoadingStart?.(),this.emit({type:"loading-start",detail:{source:"string"==typeof t?t:"file/blob"}}),this.emit({type:"loading-progress",detail:{progress:.1}});try{let i;try{i=rD(t)}catch(t){}if(i&&aD(i.ext))try{this.emit({type:"loading-progress",detail:{progress:.3}});const s={applyRotation:!1,..."number"==typeof e.maxSplats&&{maxSplats:e.maxSplats}},n=await lD(this.app,t,s);if(this.entities.splat=n.entity,this._asset=n.asset,i.url&&i.blob)try{URL.revokeObjectURL(i.url)}catch(t){}return await new Promise(t=>{this.app.once("frameupdate",()=>{this._applySplatRenderingConfigToEntity(n.entity),this.autoFocus&&(this.focus(n.entity),setTimeout(()=>{this.debugInfo().boundsRadius||this.focus(n.entity)},100)),this.isLoading=!1,this.hasModel=!0,this._onLoaded?.(n),this.emit({type:"loaded",detail:{entity:n.entity,asset:n.asset}}),t(n)})})}catch(t){throw t instanceof nD?(this.error=t.code||"UNKNOWN_LOADER_ERROR",this._onError?.(this.error)):(this.error="UNKNOWN_LOADER_ERROR",this._onError?.(this.error)),this.isLoading=!1,this.emit({type:"error",detail:{message:this.error,code:t instanceof nD?t.code:"UNKNOWN_ERROR"}}),t}let s=null,n="gsplat";if("string"==typeof t)s=t,n=t.split("/").pop()||"gsplat";else{if(!(t instanceof Blob))throw new Error("Unsupported source type");s=URL.createObjectURL(t),this._blobUrl=s,n="local.ply"}try{this.emit({type:"loading-progress",detail:{progress:.5}});const t=new T_(n,"gsplat",{url:s}),e=new dC([t],this.app.assets);if(await new Promise(t=>e.load(()=>t())),this.emit({type:"loading-progress",detail:{progress:.8}}),!t||!1===t.loaded||!t.resource)throw new Error("GSplat asset failed to load");const i=new z_("splat");return i.addComponent("gsplat",{asset:t}),i.setLocalEulerAngles(270,0,0),this.app.root.addChild(i),this.entities.splat=i,this._asset=t,await new Promise(e=>{this.app.once("frameupdate",()=>{this._applySplatRenderingConfigToEntity(i),this.autoFocus&&(this.focus(i),setTimeout(()=>{this.debugInfo().boundsRadius||this.focus(i)},100)),this.isLoading=!1,this.hasModel=!0;const s={entity:i,asset:t};this._onLoaded?.(s),this.emit({type:"loaded",detail:{entity:s.entity,asset:s.asset}}),e(s)})})}catch(t){throw this.error="Failed to load splat",this._onError?.(this.error),this.isLoading=!1,this.emit({type:"error",detail:{message:this.error,code:"LOAD_FAILED"}}),t}}catch(t){throw this.isLoading=!1,t}}focus(t){if(this._supersplat)return void this._supersplat.focus();const e=t||this.entities.splat||this.app?.root;if(e&&this._orbit)try{const t=new ut;this.calcSceneBounds(t,e);const i=t.halfExtents.length();if(this._orbit&&void 0!==this._orbit.distance){const t=2.5*i;this._orbit.distance=t}const s=this.calcFocalPoint(t);if(this.initialCameraPosition)return this.initialCameraPosition=null,void(this._orbit&&void 0!==this._orbit.target&&(this._orbit.target=s));this._orbit&&void 0!==this._orbit.target&&(this._orbit.target=s),"function"==typeof this._orbit.focus&&this._orbit.focus(e)}catch(t){"function"==typeof this._orbit.focus&&this._orbit.focus(e)}}calcSceneBounds(t,e){if(e)if(t.center.set(0,0,0),t.halfExtents.set(0,0,0),e.getWorldTransform&&e.getWorldTransform(),e._calculateHierarchyBounds)e._calculateHierarchyBounds(t);else if(e.gsplat){const i=e.gsplat;if(i.bounds)t.copy(i.bounds);else if(i.boundingBox)t.copy(i.boundingBox);else if(i.instance&&i.instance.meshInstance){const e=i.instance.meshInstance;e.aabb&&t.copy(e.aabb)}else if(i.asset&&i.asset.resource){const e=i.asset.resource;e&&e.aabb&&t.copy(e.aabb)}}}calcFocalPoint(t){return t.center.clone()}async addModel(t,e={}){if(this._supersplat)return await this._supersplatReady,await this._supersplat.addModel(t,e);if(!this._modelManager)throw new Error("SplatViewerCore.addModel: ModelManager not initialized");const i=await this._modelManager.addModel(t,e);return i?.entity&&this._applySplatRenderingConfigToEntity(i.entity),i}removeModel(t){if(this._supersplat)this._supersplat.removeModel(t);else{if(!this._modelManager)throw new Error("SplatViewerCore.removeModel: ModelManager not initialized");this._modelManager.removeModel(t)}}getModels(){return this._supersplat?this._supersplat.getModels():this._modelManager?this._modelManager.getModels():[]}getModelStats(t){if(this._supersplat)return this._supersplat.getModelStats(t);if(!this._modelManager)throw new Error("SplatViewerCore.getModelStats: ModelManager not initialized");return this._modelManager.getModelStats(t)}getAllModelStats(){return this._supersplat?this._supersplat.getAllModelStats():this._modelManager?this._modelManager.getAllModelStats():{}}getSceneStats(){return this._supersplat?this._supersplat.getSceneStats():this._modelManager?this._modelManager.getSceneStats():{modelCount:0,totalSplats:0,totalFileSize:0,totalMemoryUsage:0,bounds:{center:{x:0,y:0,z:0},halfExtents:{x:0,y:0,z:0}}}}setFlyCameraSpeed(t){t<=0||!isFinite(t)||this.setFlyCameraConfig({moveSpeed:t})}getFlyCameraSpeed(){const t=this.getFlyCameraConfig();return t?t.moveSpeed:null}setModelVisible(t,e){if(this._supersplat)this._supersplat.setModelVisible(t,e);else{if(!this._modelManager)throw new Error("SplatViewerCore.setModelVisible: ModelManager not initialized");this._modelManager.setModelVisible(t,e)}}setModelsVisibleByName(t,e){if(this._supersplat)this._supersplat.setModelsVisibleByName(t,e);else{if(!this._modelManager)throw new Error("SplatViewerCore.setModelsVisibleByName: ModelManager not initialized");this._modelManager.setModelsVisibleByName(t,e)}}setSplatCenterSize(t){if(!isFinite(t)||t<=0)return;const e=this._splatCenterSize;this._splatCenterSize=t,this._forEachSplatEntity(t=>{this._applySplatRenderingConfigToEntity(t)}),this.emit({type:"splat-center-size-changed",detail:{size:t,previousSize:e??t}})}getSplatCenterSize(){return this._splatCenterSize}setSphericalHarmonicsBands(t){if(!isFinite(t))return;const e=Math.max(0,Math.min(3,Math.round(t))),i=this._sphericalHarmonicsBands;this._sphericalHarmonicsBands=e,this._forEachSplatEntity(t=>{this._applySplatRenderingConfigToEntity(t)}),this.emit({type:"spherical-harmonics-bands-changed",detail:{bands:e,previousBands:i??e}})}getSphericalHarmonicsBands(){return this._sphericalHarmonicsBands}setGridEnabled(t){if(this._supersplat)return this._supersplat.setGridEnabled(t),void(this._gridEnabled=t);if(!this.app)throw new Error("SplatViewerCore.setGridEnabled: PlayCanvas app not initialized. Call init() first.");this._gridEnabled=t,t&&!this._infiniteGrid&&this._setupInfiniteGrid(),this._infiniteGrid&&(this._infiniteGrid.visible=t)}isGridEnabled(){return this._supersplat?this._supersplat.isGridEnabled():this._gridEnabled}_setupInfiniteGrid(){this.app&&!this._infiniteGrid&&(this._infiniteGrid=new sD(this.app,()=>this.entities.camera||null))}_setupBoxSelection(){if(!this.app&&this._supersplat){const t=this._supersplat.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)}this.app&&!this._boxSelectionAPI&&(this._boxSelectionAPI=new Nz,this._boxSelectionAPI.initialize(this.app,this.app.root,this.entities.camera||null,(t,e)=>this.emit({type:t,detail:e})),this._boxSelectionAPI.setCameraControlCallback(t=>{if(this._supersplat?.setCameraControlsEnabled?.(t),this._orbit){const e=this._orbit;"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t),void 0!==e._inputEnabled&&(e._inputEnabled=t)}}),this.app.on("prerender",()=>{this._boxSelectionAPI?.update()}))}createSelectionBox(t){return this._boxSelectionAPI||(this._setupBoxSelection(),this._boxSelectionAPI)?this._boxSelectionAPI.createBox(t):null}removeSelectionBox(t){return!!this._boxSelectionAPI&&this._boxSelectionAPI.removeBox(t)}clearSelectionBoxes(){this._boxSelectionAPI?.clear()}setBoxSize(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxSize(t,e,i,s)}getBoxSize(t){return this._boxSelectionAPI?.getBoxSize(t)??null}setBoxPosition(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxPosition(t,e,i,s)}getBoxPosition(t){return this._boxSelectionAPI?.getBoxPosition(t)??null}setBoxColor(t,e,i,s){return!!this._boxSelectionAPI&&this._boxSelectionAPI.setBoxColor(t,e,i,s)}showBox(t,e){return!!this._boxSelectionAPI&&this._boxSelectionAPI.showBox(t,e)}getAllSelectionBoxes(){return this._boxSelectionAPI?.getAllBoxes()??[]}getSelectedBoxId(){return this._boxSelectionAPI?.getSelectedBoxId()??null}selectBox(t){return!!this._boxSelectionAPI&&this._boxSelectionAPI.selectBox(t)}setBoxSelectionEnabled(t){this._boxSelectionEnabled=t,t&&!this._boxSelectionAPI&&this.app&&this._setupBoxSelection(),this._boxSelectionAPI&&this._boxSelectionAPI.setInteractionEnabled(t)}isBoxSelectionEnabled(){return this._boxSelectionEnabled}_setupSphereSelection(){if(!this.app&&this._supersplat){const t=this._supersplat.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)}this.app&&!this._sphereSelectionAPI&&(this._sphereSelectionAPI=new Uz,this._sphereSelectionAPI.initialize(this.app,this.app.root,this.entities.camera||null,(t,e)=>this.emit({type:t,detail:e})),this._sphereSelectionAPI.setCameraControlCallback(t=>{if(this._supersplat?.setCameraControlsEnabled?.(t),this._orbit){const e=this._orbit;"function"==typeof e.setEnabled?e.setEnabled(t):"enabled"in e&&(e.enabled=t),void 0!==e._inputEnabled&&(e._inputEnabled=t)}}),this.app.on("prerender",()=>{this._sphereSelectionAPI?.update()}))}createSelectionSphere(t){return this._sphereSelectionAPI||(this._setupSphereSelection(),this._sphereSelectionAPI)?this._sphereSelectionAPI.createSphere(t):null}removeSelectionSphere(t){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.removeSphere(t)}clearSelectionSpheres(){this._sphereSelectionAPI?.clear()}setSphereRadius(t,e){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSphereRadius(t,e)}getSphereRadius(t){return this._sphereSelectionAPI?.getSphereRadius(t)??null}setSpherePosition(t,e,i,s){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSpherePosition(t,e,i,s)}getSpherePosition(t){return this._sphereSelectionAPI?.getSpherePosition(t)??null}setSphereColor(t,e,i,s){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.setSphereColor(t,e,i,s)}showSphere(t,e){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.showSphere(t,e)}getAllSelectionSpheres(){return this._sphereSelectionAPI?.getAllSpheres()??[]}getSelectedSphereId(){return this._sphereSelectionAPI?.getSelectedSphereId()??null}setSphereSelectionEnabled(t){this._sphereSelectionEnabled=t,t&&!this._sphereSelectionAPI&&this.app&&this._setupSphereSelection(),this._sphereSelectionAPI&&this._sphereSelectionAPI.setInteractionEnabled(t)}isSphereSelectionEnabled(){return this._sphereSelectionEnabled}selectSphere(t){return!!this._sphereSelectionAPI&&this._sphereSelectionAPI.selectSphere(t)}getSplatDataDebugInfo(t){if(!this._splatSelectionManager)return{error:"SplatSelectionManager not initialized"};let e=this.entities.splat;if(t&&this._modelManager){const i=this._modelManager.getModelById(t);i?.entity&&(e=i.entity)}return this._splatSelectionManager.getDebugInfo(e)}extractSplatData(t){if(!this._splatSelectionManager)return null;let e=this.entities.splat;if(t&&this._modelManager){const i=this._modelManager.getModelById(t);i?.entity&&(e=i.entity)}return e?this._splatSelectionManager.extractSplatData(e):null}selectSplatsInBox(t,e,i=!1){if(this._supersplat){const e=this._boxSelectionAPI?.getBoxProperties(t);if(!e)return null;const s={minX:e.position.x-e.size.x/2,maxX:e.position.x+e.size.x/2,minY:e.position.y-e.size.y/2,maxY:e.position.y+e.size.y/2,minZ:e.position.z-e.size.z/2,maxZ:e.position.z+e.size.z/2};return this._supersplat.selectInBox(s,i)}if(!this._splatSelectionManager||!this._boxSelectionAPI)return null;const s=this._boxSelectionAPI.getBoxProperties(t);if(!s)return null;let n=this.entities.splat;if(e&&this._modelManager){const t=this._modelManager.getModelById(e);t?.entity&&(n=t.entity)}if(!n)return null;const r={minX:s.position.x-s.size.x/2,maxX:s.position.x+s.size.x/2,minY:s.position.y-s.size.y/2,maxY:s.position.y+s.size.y/2,minZ:s.position.z-s.size.z/2,maxZ:s.position.z+s.size.z/2},a=this._splatSelectionManager.selectSplatsInBox(n,r,i);return this._updateHighlightOverlay(n,a),a}selectSplatsInSphere(t,e,i,s=!1){if(this._supersplat){const i={cx:t.x,cy:t.y,cz:t.z,radius:e};return this._supersplat.selectInSphere(i,s)}if(!this._splatSelectionManager)return null;let n=this.entities.splat;if(i&&this._modelManager){const t=this._modelManager.getModelById(i);t?.entity&&(n=t.entity)}if(!n)return null;const r={cx:t.x,cy:t.y,cz:t.z,radius:e},a=this._splatSelectionManager.selectSplatsInSphere(n,r,s);return this._updateHighlightOverlay(n,a),a}selectSplatsInSphereById(t,e,i=!1){if(this._supersplat){const e=this._sphereSelectionAPI?.getSphereProperties(t);if(!e)return null;const s={cx:e.position.x,cy:e.position.y,cz:e.position.z,radius:e.radius};return this._supersplat.selectInSphere(s,i)}if(!this._splatSelectionManager)return null;const s=this._sphereSelectionAPI?.getSphereProperties(t);if(!s)return null;let n=this.entities.splat;if(e&&this._modelManager){const t=this._modelManager.getModelById(e);t?.entity&&(n=t.entity)}if(!n)return null;const r={cx:s.position.x,cy:s.position.y,cz:s.position.z,radius:s.radius},a=this._splatSelectionManager.selectSplatsInSphere(n,r,i);return this._updateHighlightOverlay(n,a),a}clearSplatSelection(){this._supersplat?this._supersplat.clearSelection():(this._splatSelectionManager?.clearSelection(),this._splatHighlightOverlay?.clear())}getSelectedSplats(){return this._supersplat?this._supersplat.getSelectedIndices():this._splatSelectionManager?.getSelectedIndices()??new Uint32Array(0)}setHighlightEnabled(t){this._highlightEnabled=t,this._supersplat||(this._splatHighlightOverlay&&(this._splatHighlightOverlay.setEnabled(t),t||this._splatHighlightOverlay.clear()),this._splatHighlightShader&&this._splatHighlightShader.setEnabled(t))}isHighlightEnabled(){return this._highlightEnabled}setHighlightColor(t,e,i,s=.7){this._supersplat?this._supersplat.setHighlightColor(t,e,i,s):(this._splatHighlightShader?.setHighlightColor(t,e,i,s),this._splatHighlightOverlay?.setColor(t,e,i,s))}getHighlightColor(){return this._splatHighlightShader?this._splatHighlightShader.getConfig().color:null}setHighlightMode(t){this._splatHighlightShader?.setHighlightMode(t)}getHighlightMode(){return this._splatHighlightShader?this._splatHighlightShader.getConfig().mode:null}setHighlightOverlayStyle(t){this._splatHighlightOverlay?.setStyle(t)}setHighlightOverlaySize(t){this._splatHighlightOverlay?.setPointSize(t)}setOutlineEnabled(t){this._outlineEnabled=t,this._splatHighlightShader?.setEnabled(t)}isOutlineEnabled(){return this._outlineEnabled}_updateHighlightOverlay(t,e){if(!this._splatHighlightOverlay||!this._splatSelectionManager||!e)return;const i=this._splatSelectionManager.extractSplatData(t);i.hasPositions&&i.x&&i.y&&i.z?this._splatHighlightOverlay.updateSelectionFromSplatData(i.x,i.y,i.z,Array.from(e.indices),t.getWorldTransform?t.getWorldTransform():void 0):this._splatHighlightOverlay.clear()}setBoundingBoxEnabled(t){if(this._boundingBoxEnabled=t,t){if(!this.app&&this._supersplat){const t=()=>{if(this.app)return;const t=this._supersplat?.getPlayCanvasContext?.();t?.app&&(this.app=t.app,this.entities.camera=t.camera||null)};if(t(),!this.app&&this._supersplatReady)return void this._supersplatReady.then(()=>{t(),this._boundingBoxEnabled&&this.app&&!this._boundingBoxRenderHandler&&this._setupBoundingBoxRenderer()}).catch(t=>{})}if(!this.app)throw new Error("SplatViewerCore.setBoundingBoxEnabled: PlayCanvas app not initialized. Call init() first.");this._boundingBoxRenderHandler||this._setupBoundingBoxRenderer()}}isBoundingBoxEnabled(){return this._boundingBoxEnabled}setBoundingBoxSelection(t){t!==this._selectedModelIdForBoundingBox&&(this._selectedModelIdForBoundingBox=t)}getBoundingBoxSelection(){return this._selectedModelIdForBoundingBox}_setupBoundingBoxRenderer(){if(!this.app||this._boundingBoxRenderHandler)return;const t=this.app,e=new ut,i=new H(1,1,1);this._boundingBoxRenderHandler=()=>{if(!this._boundingBoxEnabled)return;let s=null;if(this._modelManager&&this._selectedModelIdForBoundingBox){const t=this._modelManager.getModelById(this._selectedModelIdForBoundingBox);t&&t.entity&&(s=t.entity)}if(!s&&this.entities.splat&&(s=this.entities.splat),!s)return;this.calcSceneBounds(e,s);const n=e.halfExtents;if(!n||0===n.length())return;const r=e.center,a=r.x-n.x,o=r.x+n.x,l=r.y-n.y,h=r.y+n.y,c=r.z-n.z,d=r.z+n.z,u=new K(a,l,c),p=new K(a,l,d),f=new K(a,h,c),m=new K(a,h,d),_=new K(o,l,c),g=new K(o,l,d),v=new K(o,h,c),y=new K(o,h,d),S=!0;t.drawLine(u,_,i,S),t.drawLine(_,g,i,S),t.drawLine(g,p,i,S),t.drawLine(p,u,i,S),t.drawLine(f,v,i,S),t.drawLine(v,y,i,S),t.drawLine(y,m,i,S),t.drawLine(m,f,i,S),t.drawLine(u,f,i,S),t.drawLine(_,v,i,S),t.drawLine(g,y,i,S),t.drawLine(p,m,i,S)},t.on("update",this._boundingBoxRenderHandler)}_applySplatRenderingConfigToEntity(t){const e=t.gsplat;if(e){if(null!=this._splatCenterSize){const t=this._splatCenterSize;if("centerSize"in e&&(e.centerSize=t),"centersSize"in e&&(e.centersSize=t),"pointSize"in e&&(e.pointSize=t),e.settings&&("centerSize"in e.settings&&(e.settings.centerSize=t),"centersSize"in e.settings&&(e.settings.centersSize=t),"pointSize"in e.settings&&(e.settings.pointSize=t)),e.instance&&("centerSize"in e.instance&&(e.instance.centerSize=t),"centersSize"in e.instance&&(e.instance.centersSize=t),"pointSize"in e.instance&&(e.instance.pointSize=t),e.instance.renderOptions)){const i=e.instance.renderOptions;"centerSize"in i&&(i.centerSize=t),"centersSize"in i&&(i.centersSize=t),"pointSize"in i&&(i.pointSize=t)}}if(null!=this._sphericalHarmonicsBands){const t=this._sphericalHarmonicsBands;"shBands"in e&&(e.shBands=t),"shBandCount"in e&&(e.shBandCount=t),"sphericalHarmonicsBands"in e&&(e.sphericalHarmonicsBands=t),e.settings&&("shBands"in e.settings&&(e.settings.shBands=t),"shBandCount"in e.settings&&(e.settings.shBandCount=t),"sphericalHarmonicsBands"in e.settings&&(e.settings.sphericalHarmonicsBands=t)),e.instance&&("shBands"in e.instance&&(e.instance.shBands=t),"shBandCount"in e.instance&&(e.instance.shBandCount=t),"sphericalHarmonicsBands"in e.instance&&(e.instance.sphericalHarmonicsBands=t))}this._splatHighlightShader&&this._splatHighlightShader.applyUniforms(e)}}_forEachSplatEntity(t){if(this.entities.splat&&t(this.entities.splat),this._supersplat){const e=this._supersplat.getModels();for(const i of e)i.entity&&t(i.entity)}if(this._modelManager){const e=this._modelManager.getModels();for(const i of e)i.entity&&t(i.entity)}}applyTransformMatrix(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.applyTransformMatrix: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.applyTransformMatrix");this._transformSystem.applyTransformMatrix(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelPosition(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelPosition: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelPosition");this._transformSystem.setPosition(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelRotation(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelRotation: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelRotation");this._transformSystem.setRotation(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}setModelScale(t,e){if(!this._transformSystem)throw new Error("SplatViewerCore.setModelScale: TransformSystem not initialized");const i=this._resolveModelEntityForId(t,"SplatViewerCore.setModelScale");this._transformSystem.setScale(i,e,t);const s=this._transformSystem.getTransform(i);this._supersplat?this._supersplat.updateModelTransform(t,s):this._modelManager&&this._modelManager.updateModelTransform(t,s)}getModelTransform(t){if(!this._transformSystem)throw new Error("SplatViewerCore.getModelTransform: TransformSystem not initialized");const e=this._resolveModelEntityForId(t,"SplatViewerCore.getModelTransform");return this._transformSystem.getTransform(e)}resetModelTransform(t){if(!this._transformSystem)throw new Error("SplatViewerCore.resetModelTransform: TransformSystem not initialized");const e=this._resolveModelEntityForId(t,"SplatViewerCore.resetModelTransform");this._transformSystem.resetTransform(e,t);const i=this._transformSystem.getTransform(e);this._supersplat?this._supersplat.updateModelTransform(t,i):this._modelManager&&this._modelManager.updateModelTransform(t,i)}clear(){if(this._supersplat)this._supersplat.clear(),this.entities.splat=null;else{if(this._modelManager&&this._modelManager.clear(),this.entities.splat&&(this.entities.splat.destroy(),this.entities.splat=null),this._asset){this._asset.unload();try{this.app?.assets?.remove?.(this._asset)}catch{}const t=this._asset;"function"==typeof t.destroy&&t.destroy(),this._asset=null}this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}this.hasModel=!1,this.error=null,this._selectedModelIdForBoundingBox=null,this._boxSelectionAPI?.clear(),this._sphereSelectionAPI?.clear(),this._splatSelectionManager?.clearSelection(),this._splatSelectionManager?.clearCache(),this._splatHighlightOverlay?.clear()}destroy(){if(this.app){if(this.clear(),this._infiniteGrid){try{this._infiniteGrid.destroy()}catch{}this._infiniteGrid=null}if(this._boundingBoxRenderHandler){try{this.app.off("update",this._boundingBoxRenderHandler)}catch{}this._boundingBoxRenderHandler=null}this._modelManager=null,this._boxSelectionAPI?.clear(),this._boxSelectionAPI=null,this._sphereSelectionAPI?.clear(),this._sphereSelectionAPI=null,this._splatSelectionManager?.destroy(),this._splatSelectionManager=null,this._splatHighlightOverlay?.destroy(),this._splatHighlightOverlay=null,this._splatHighlightShader?.isShaderApplied()&&this._splatHighlightShader.restoreOriginalShader(),this._splatHighlightShader=null,this._statsHandler&&(this.app.off("frameend",this._statsHandler),this._statsHandler=null),this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._resizeHandler&&(window.removeEventListener("resize",this._resizeHandler),this._resizeHandler=null);try{this.entities.camera&&(this.entities.camera.destroy(),this.entities.camera=null)}catch(t){}try{this.entities.light&&(this.entities.light.destroy(),this.entities.light=null)}catch(t){}try{this.app.destroy()}catch(t){throw t}this.app=null,this._orbit=null}}debugInfo(){const t=this._asset,e=this.entities.splat,i=!!e?.gsplat;let s=null,n=null;if(e){const t=e.gsplat;if(t){const e=t.bounds||t.boundingBox||null;e?.halfExtents?(s=Math.max(1,e.halfExtents.length()),n="gsplat.bounds"):"number"==typeof t.radius&&(s=Math.max(1,t.radius),n="gsplat.radius")}if(null==s&&e._calculateHierarchyBounds){const t=new ut;e.getWorldTransform(),e._calculateHierarchyBounds(t),t.halfExtents.length()>0&&(s=Math.max(1,t.halfExtents.length()),n="hierarchy")}}return{assetName:t?.name||null,assetUrl:t?.file?.url||t?.url||null,hasEntity:!!e,hasGsplatComponent:i,cameraDistance:this._orbit?.distance??null,boundsRadius:s,boundsSource:n,cameraTarget:this._orbit?.target?this._orbit.target.toString():null}}on(t,e){this._eventListeners.has(t)||this._eventListeners.set(t,new Set),this._eventListeners.get(t).add(e)}off(t,e){const i=this._eventListeners.get(t);i&&(i.delete(e),0===i.size&&this._eventListeners.delete(t))}emit(t){const e=this._eventListeners.get(t.type);e&&e.forEach(e=>{try{e(t)}catch(t){}})}setCameraPosition(t){this.entities.camera&&(this.entities.camera.setPosition(t),this.emit({type:"camera-change",detail:{position:t,target:this._orbit?.target||{x:0,y:0,z:0}}}))}setCameraTarget(t){this._orbit&&(this._orbit.target=t,this._orbit.updateCameraPosition?.(),this.emit({type:"camera-change",detail:{position:this.entities.camera?.getPosition?.()||{x:0,y:0,z:0},target:t}}))}resetCamera(){this._orbit&&(this._orbit.target={x:0,y:0,z:0},this._orbit.distance=10,this._orbit.pitch=-15,this._orbit.yaw=45,this._orbit.updateCameraPosition?.(),this.emit({type:"camera-change",detail:{position:this.entities.camera?.getPosition?.()||{x:0,y:0,z:0},target:{x:0,y:0,z:0}}}))}async setSkyboxEnabled(t){const e=this.app??this._supersplat?.getPlayCanvasContext?.()?.app;if(!e)return void(this._skyboxEnabled=!!t);const i=e.scene;if(t===this._skyboxEnabled&&i?.skybox)return;if(!t)return this._skyboxEnabled=!1,void(i&&"skybox"in i&&(i.skybox=null));if(this._skyboxLoadingPromise)return await this._skyboxLoadingPromise,void(this._skyboxEnabled=!0);const s=this._loadDefaultSkyboxCubemap(e);this._skyboxLoadingPromise=s;try{await s,this._skyboxEnabled=!0}catch(t){throw this._skyboxEnabled=!1,t}finally{this._skyboxLoadingPromise===s&&(this._skyboxLoadingPromise=null)}}isSkyboxEnabled(){return this._skyboxEnabled}async _loadDefaultSkyboxCubemap(t){const e=t??this.app??null;if(!e)return;const i=e.scene;if(i&&i.skybox)return;const s="/assets/skybox",n=["skybox_px.jpg","skybox_nx.jpg","skybox_py.jpg","skybox_ny.jpg","skybox_pz.jpg","skybox_nz.jpg"].map(t=>`${s}/${t}`).map((t,i)=>{const s=new T_(`skybox-face-${i}`,"texture",{url:t});try{e.assets?.add?.(s)}catch{}return s}),r=new dC(n,e.assets);if(await new Promise((t,e)=>{r.load(i=>{i?e(new Error(`SplatViewerCore: Failed to load skybox textures from ${s}: ${i}`)):t()})}),!n[0]||!n[0].resource)throw new Error("SplatViewerCore: Skybox textures loaded but no texture resource was found.");n[0].resource;const a=Gi;if(!a)return;const o=n.map((t,e)=>{if(!t||!t.resource)throw new Error(`SplatViewerCore: Missing skybox face texture at index ${e}.`);return t.resource}),l=o[0],h=Array.isArray(l._levels)&&l._levels.length>0?l._levels.length:0;if(0===h)return;const c=[];for(let t=0;t<h;t++)c.push(o.map(e=>e._levels[t]));const d=6===l.format?7:l.format,u=new a(e.graphicsDevice,{name:"splat-viewer-skybox",cubemap:!0,type:l.type,width:l.width,height:l.height,format:d,mipmaps:!0,levels:c,minFilter:l.minFilter,magFilter:l.magFilter,anisotropy:"number"==typeof l.anisotropy?l.anisotropy:1,addressU:1,addressV:1});i&&(i.skybox=u)}setCameraMode(t){if(!this.previewMode){if(this._supersplat){const e=this._cameraMode;if(t===e)return;if(!this._fly)try{this._setupFlyCameraForSupersplat()}catch{}if("fly"===t){if(this._supersplat.setCameraControlsEnabled(!1),this._supersplat.setCameraManualControl(!0),this._fly)if("function"==typeof this._fly.syncFromEntity)this._fly.syncFromEntity();else try{const t=this.entities.camera?.getPosition?.();if(t){const e=t.clone?t.clone():new K(t.x||0,t.y||0,t.z||0);this.entities.camera?.setPosition?.(e)}const e=this.entities.camera?.getEulerAngles?.();e&&(this._fly._pitch=e.x||0,this._fly._yaw=e.y||0)}catch{}this._fly?.activate?.(),this._cameraMode="fly"}else this._fly?.deactivate?.(),this._supersplat.setCameraManualControl(!1),this._supersplat.setCameraControlsEnabled(!0),this._supersplat.syncOrbitFromCameraEntity?.(new K(0,0,0)),this._cameraMode="orbit";return void this.emit({type:"camera-mode-changed",detail:{mode:this._cameraMode,previousMode:e}})}this._cameraModeManager&&this._cameraModeManager.setMode(t)}}setCameraFOV(t){if(this._supersplat?.setCameraFOV){const e=this._supersplat.getCameraFOV?.()??t;return this._supersplat.setCameraFOV(t),void this.emit({type:"camera-fov-changed",detail:{fov:t,previousFov:e}})}this._sceneConfigManager&&this._sceneConfigManager.setCameraFOV(t)}getCameraFOV(){return this._supersplat?.getCameraFOV?this._supersplat.getCameraFOV():this._sceneConfigManager?this._sceneConfigManager.getCameraFOV():this.entities.camera?.camera?.fov??60}async animateCameraFOV(t,e){if(this._supersplat?.setCameraFOV&&this._supersplat?.getCameraFOV){const i=this._supersplat.getCameraFOV(),s=performance.now(),n=Math.max(0,Number(e)||0),r=t=>Math.max(1,Math.min(179,t)),a=r(t);return 0===n?(this._supersplat.setCameraFOV(a),void this.emit({type:"camera-fov-changed",detail:{fov:a,previousFov:i}})):void await new Promise(t=>{const e=()=>{const o=performance.now(),l=Math.min(1,(o-s)/n),h=i+(a-i)*l;if(this._supersplat.setCameraFOV(r(h)),l>=1)return this.emit({type:"camera-fov-changed",detail:{fov:a,previousFov:i}}),void t();requestAnimationFrame(e)};requestAnimationFrame(e)})}this._sceneConfigManager&&await this._sceneConfigManager.animateCameraFOV(t,e)}setBackgroundColor(t){this._sceneConfigManager&&this._sceneConfigManager.setBackgroundColor(t)}getBackgroundColor(){return this._sceneConfigManager?this._sceneConfigManager.getBackgroundColor():{r:26,g:26,b:26,a:1}}async animateBackgroundColor(t,e){this._sceneConfigManager&&await this._sceneConfigManager.animateBackgroundColor(t,e)}getCameraMode(){return this._supersplat?this._cameraMode:this._cameraModeManager?.getMode()||"orbit"}setFlyCameraConfig(t){this._supersplat&&this._fly?.setConfig?this._fly.setConfig(t):this._cameraModeManager?.setFlyConfig(t)}getFlyCameraConfig(){if(this._supersplat&&this._fly)try{const t=this._fly;return{moveSpeed:t.moveSpeed,fastSpeedMultiplier:t.fastSpeedMultiplier,slowSpeedMultiplier:t.slowSpeedMultiplier,lookSensitivity:t.lookSensitivity,invertY:!!t.invertY,keyBindings:{...t.keyBindings||{}},smoothing:t.smoothing,friction:t.friction,enableCollision:!!t.enableCollision,minHeight:t.minHeight??null,maxHeight:t.maxHeight??null}}catch{return null}return this._cameraModeManager?.getFlyConfig()||null}getFlyCameraState(){if(this._supersplat&&this._fly?.getState)try{const t=this._fly.getState();return{mode:this._cameraMode,position:t.position,rotation:t.rotation,velocity:t.velocity,isMoving:t.isMoving}}catch{return null}return this._cameraModeManager?.getFlyState()||null}_setupScene(){this.app&&(this.app.scene.ambientLight=new H(.2,.2,.2))}_setupCamera(){if(!this.app)return;const t=new z_("camera");t.addComponent("camera",{clearColor:new H(.1,.1,.1),nearClip:.01,farClip:1e6}),this.app.root.addChild(t),this.entities.camera=t}_setupLighting(){if(!this.app)return;const t=new z_("light");t.addComponent("light",{type:0,color:new H(1,1,1),intensity:1,castShadows:!0}),t.setLocalEulerAngles(45,30,0),this.app.root.addChild(t),this.entities.light=t}_setupOrbitCamera(){if(!this.app||!this.entities.camera)return;!function(){if(void 0===JL)return;if(!n_)return;if(n_?.scripts?.has("orbitCamera"))return;const t=Lw("orbitCamera");t&&(t.attributes.add("distance",{type:"number",default:10}),t.attributes.add("minDistance",{type:"number",default:.1}),t.attributes.add("maxDistance",{type:"number",default:1e5}),t.attributes.add("orbitSensitivity",{type:"number",default:.3}),t.attributes.add("panSensitivity",{type:"number",default:1}),t.attributes.add("zoomSensitivity",{type:"number",default:.1}),t.attributes.add("enableNavigationCube",{type:"boolean",default:!1}),t.attributes.add("navigationCubeConfig",{type:"json",default:null}),t.prototype.initialize=function(){if(this.target=new K(0,0,0),this.distance=this.distance||10,this.pitch=-15,this.yaw=45,this.isOrbiting=!1,this.isPanning=!1,this._inputEnabled=!0,this._orbitEnabled=!0,this._panEnabled=!0,this._zoomEnabled=!0,this.setupContextMenuPrevention(),this.app.mouse.on(fM,this.onMouseDown,this),this.app.mouse.on(_M,this.onMouseUp,this),this.app.mouse.on(mM,this.onMouseMove,this),this.app.mouse.on(gM,this.onMouseWheel,this),this.updateCameraPosition(),this.enableNavigationCube)try{let t=this.navigationCubeConfig||{};this.entity._navigationCubeConfig&&(t=this.entity._navigationCubeConfig),this.navigationCube=new Pz(t),this.navigationCube.initialize(this.app,this.entity,this,this.emitInteractionEvent)}catch(t){delete this.navigationCube}},t.prototype.setEnabled=function(t){this._inputEnabled=!!t,t||(this.isOrbiting=!1,this.isPanning=!1)},t.prototype.setInputControls=function(t){void 0!==t.orbit&&(this._orbitEnabled=!!t.orbit),void 0!==t.pan&&(this._panEnabled=!!t.pan),void 0!==t.zoom&&(this._zoomEnabled=!!t.zoom),!1===this._orbitEnabled&&(this.isOrbiting=!1),!1===this._panEnabled&&(this.isPanning=!1)},t.prototype.update=function(t){this.navigationCube&&"function"==typeof this.navigationCube.update&&this.navigationCube.update(t)},t.prototype.onMouseDown=function(t){!1!==this._inputEnabled&&(this.navigationCube&&"function"==typeof this.navigationCube.cancelTransition&&this.navigationCube.cancelTransition("manual-interaction"),0===t.button&&!1!==this._orbitEnabled?(this.isOrbiting=!0,this.emitInteractionEvent?.("interaction-start","rotate")):2!==t.button&&1!==t.button||!1===this._panEnabled||(this.isPanning=!0,this.emitInteractionEvent?.("interaction-start","pan")))},t.prototype.onMouseUp=function(){this.isOrbiting&&(this.isOrbiting=!1,this.emitInteractionEvent?.("interaction-end","rotate")),this.isPanning&&(this.isPanning=!1,this.emitInteractionEvent?.("interaction-end","pan"))},t.prototype.onMouseMove=function(t){if(!1!==this._inputEnabled)if(this.isOrbiting){const e=t.dx*this.orbitSensitivity,i=t.dy*this.orbitSensitivity;this.yaw-=e,this.pitch+=i,this.pitch=Math.max(-89,Math.min(89,this.pitch)),this.updateCameraPosition()}else if(this.isPanning){const e=this.distance*this.panSensitivity*.001,i=this.entity.getWorldTransform(),s=new K,n=new K;i.getX(s),i.getY(n);const r=s.clone().mulScalar(-t.dx*e).add(n.clone().mulScalar(t.dy*e));this.target.add(r),this.updateCameraPosition()}},t.prototype.onMouseWheel=function(t){if(!1===this._inputEnabled||!1===this._zoomEnabled)return;this.navigationCube&&"function"==typeof this.navigationCube.cancelTransition&&this.navigationCube.cancelTransition("manual-interaction"),this.emitInteractionEvent?.("interaction-start","zoom");const e=Math.sign(t.wheel)*this.distance*this.zoomSensitivity;this.distance=Math.max(this.minDistance,Math.min(this.maxDistance,this.distance-e)),this.updateCameraPosition(),this.emitInteractionEvent?.("interaction-end","zoom")},t.prototype.updateCameraPosition=function(){const t=this.pitch*Math.PI/180,e=this.yaw*Math.PI/180,i=this.distance*Math.cos(t)*Math.sin(e),s=this.distance*Math.sin(t),n=this.distance*Math.cos(t)*Math.cos(e);this.entity.setPosition(new K(i,s,n).add(this.target)),this.entity.lookAt(this.target,K.UP),this.navigationCube&&"function"==typeof this.navigationCube.syncWithCamera&&this.navigationCube.syncWithCamera(this.pitch,this.yaw)},t.prototype.focus=function(t){const e=new K(0,0,0);let i=10,s=!1;if(t){const n=t.gsplat;if(n){const t=n.bounds||n.boundingBox;t?.center&&t.halfExtents?(e.copy(t.center),i=Math.max(1,t.halfExtents.length()),s=!0):"number"==typeof n.radius&&n.center&&(e.copy(n.center),i=Math.max(1,n.radius),s=!0)}if(!s&&t._calculateHierarchyBounds){const n=new ut;t.getWorldTransform(),t._calculateHierarchyBounds(n),n.halfExtents.length()>0&&(e.copy(n.center),i=Math.max(1,n.halfExtents.length()),s=!0)}}const n=this.entity.camera.fov*Math.PI/180,r=i/Math.sin(n/2)*1.5;this.target.copy(e),this.distance=Math.max(this.minDistance,Math.min(this.maxDistance,r)),this.pitch=-15,this.yaw=45,this.updateCameraPosition()},t.prototype.setupContextMenuPrevention=function(){[this.app.graphicsDevice.canvas,document.querySelector("canvas")].filter(Boolean).forEach(t=>{this._contextMenuHandler&&(t.removeEventListener("contextmenu",this._contextMenuHandler),t.removeEventListener("mousedown",this._mouseDownHandler),t.removeEventListener("mouseup",this._mouseUpHandler)),this._contextMenuHandler=t=>(t.preventDefault(),t.stopPropagation(),!1),this._mouseDownHandler=t=>{2===t.button&&(t.preventDefault(),t.stopPropagation())},this._mouseUpHandler=t=>{2===t.button&&(t.preventDefault(),t.stopPropagation())},t.addEventListener("contextmenu",this._contextMenuHandler,{passive:!1}),t.addEventListener("mousedown",this._mouseDownHandler,{passive:!1}),t.addEventListener("mouseup",this._mouseUpHandler,{passive:!1})})},t.prototype.destroy=function(){if(this.navigationCube&&"function"==typeof this.navigationCube.destroy){try{this.navigationCube.destroy()}catch(t){}delete this.navigationCube}[this.app?.graphicsDevice?.canvas,document.querySelector("canvas")].filter(Boolean).forEach(t=>{this._contextMenuHandler&&t.removeEventListener("contextmenu",this._contextMenuHandler),this._mouseDownHandler&&t.removeEventListener("mousedown",this._mouseDownHandler),this._mouseUpHandler&&t.removeEventListener("mouseup",this._mouseUpHandler)}),this.app?.mouse&&(this.app.mouse.off(fM,this.onMouseDown,this),this.app.mouse.off(_M,this.onMouseUp,this),this.app.mouse.off(mM,this.onMouseMove,this),this.app.mouse.off(gM,this.onMouseWheel,this))})}(),this.entities.camera.addComponent("script");const t={distance:10,minDistance:.1,maxDistance:1e5,orbitSensitivity:.3,panSensitivity:1,zoomSensitivity:.1};if(this._navigationCubeConfig&&!this.previewMode&&(t.enableNavigationCube=this._navigationCubeConfig.enabled||!1,this.entities.camera._navigationCubeConfig=this._navigationCubeConfig),this._orbit=this.entities.camera.script.create("orbitCamera",{attributes:t}),this._orbit.emitInteractionEvent=(t,e)=>{this.emit({type:t,detail:{type:e}})},this.previewMode&&this._orbit){const t=this._orbit;"function"==typeof t.setInputControls&&t.setInputControls({orbit:!1,pan:!1,zoom:!0})}if(this.entities.camera.setPosition(0,0,10),this.entities.camera.lookAt(K.ZERO),!this.previewMode)try{iD();const t={moveSpeed:iV.moveSpeed,fastSpeedMultiplier:iV.fastSpeedMultiplier,slowSpeedMultiplier:iV.slowSpeedMultiplier,lookSensitivity:iV.lookSensitivity,invertY:iV.invertY,keyBindings:iV.keyBindings,smoothing:iV.smoothing,friction:iV.friction,enableCollision:iV.enableCollision,minHeight:iV.minHeight,maxHeight:iV.maxHeight};this._fly=this.entities.camera.script.create("flyCamera",{attributes:t}),this._fly&&(this._fly.emitFlyEvent=(t,e)=>{this.emit({type:t,detail:e})}),this._fly?.deactivate&&this._fly.deactivate(),this._cameraModeManager=new tD(this.app,this.entities.camera,this._orbit,this._fly,(t,e)=>{this.emit({type:t,detail:e})},"orbit")}catch(t){}}_setupStats(){if(!this.app||!this.enableStats||!this._onStatsUpdate)return;let t=0,e=performance.now();this._statsHandler=()=>{t++;const i=performance.now(),s=i-e;if(s>=1e3){const n=Math.round(1e3*t/s),r=t=>"object"==typeof t&&null!==t?t.total||0:Number(t)||0,a=r(this.app.stats.triangles),o=r(this.app.stats.drawCalls),l={fps:n,frameTime:Math.round(s/t*100)/100,triangles:a,drawCalls:o,memoryUsage:performance.memory?Math.round(performance.memory.usedJSHeapSize/1024/1024):0};this._onStatsUpdate(l),this.emit({type:"stats-update",detail:l}),t=0,e=i}},this.app.on("frameend",this._statsHandler)}_setupResolution(){if(!this.app)return;const t=this.app.graphicsDevice.canvas;if(t.style.display||(t.style.display="block"),t.style.width||(t.style.width="100%"),t.style.height||(t.style.height="100%"),t.parentElement){const e=t.parentElement.style;e.width||(e.width="100%"),e.height||(e.height="100%")}const e=(e,i)=>{t.width===e&&t.height===i||(t.width=e,t.height=i,this.app.resizeCanvas(e,i),this._orbit&&this._orbit.navigationCube&&"function"==typeof this._orbit.navigationCube.onCanvasResize&&this._orbit.navigationCube.onCanvasResize(),this._supersplat&&"function"==typeof this._supersplat.onCanvasResize&&this._supersplat.onCanvasResize())},i=()=>{const i=t.getBoundingClientRect(),s=window.devicePixelRatio||1,n=Math.floor(i.width*s),r=Math.floor(i.height*s);e(n,r)},s=t=>{let s=null,n=null;const r=t.devicePixelContentBoxSize;if(r&&r.length>0)s=Math.ceil(r[0].inlineSize),n=Math.ceil(r[0].blockSize);else{const e=t.contentBoxSize;if(e&&e.length>0){const t=window.devicePixelRatio||1;s=Math.ceil(e[0].inlineSize*t),n=Math.ceil(e[0].blockSize*t)}}null!==s&&null!==n?e(s,n):i()};if(i(),window.ResizeObserver){this._resizeObserver=new ResizeObserver(e=>{if(!e||0===e.length)return void i();const n=e.find(e=>e.target===t);if(n)s(n);else if(e.length>0){const t=e[0];t?s(t):i()}else i()});try{this._resizeObserver.observe(t,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(t)}t.parentElement&&this._resizeObserver.observe(t.parentElement)}const n=()=>{i()};window.addEventListener("resize",n),this._resizeHandler=n}updateCanvasResolution(){if(!this.app)return;const t=this.app.graphicsDevice.canvas,e=t.getBoundingClientRect(),i=window.devicePixelRatio||1,s=Math.floor(e.width*i),n=Math.floor(e.height*i);t.width===s&&t.height===n||(t.width=s,t.height=n,this.app.resizeCanvas(s,n),this._orbit&&this._orbit.navigationCube&&"function"==typeof this._orbit.navigationCube.onCanvasResize&&this._orbit.navigationCube.onCanvasResize(),this._supersplat&&"function"==typeof this._supersplat.onCanvasResize&&this._supersplat.onCanvasResize())}}function sV(t,e){return new CustomEvent(t,{detail:e})}class SplatViewerElement extends HTMLElement{constructor(){super(...arguments),this._core=null,this._canvas=null,this._config={...wz},this._isInitialized=!1,this._isDestroyed=!1,this._hostResizeObserver=null}static get observedAttributes(){return["src","width","height","enable-stats","auto-focus","max-splats","preview-mode","camera-position","camera-target","orbit-sensitivity","pan-sensitivity","zoom-sensitivity","min-distance","max-distance","enable-navigation-cube","navigation-cube-size","navigation-cube-transition","navigation-cube-parent-id"]}get src(){return this.getAttribute("src")}get width(){return this.getAttribute("width")}get height(){return this.getAttribute("height")}get enableStats(){return this.hasAttribute("enable-stats")}get autoFocus(){return this.hasAttribute("auto-focus")}get previewMode(){return this.hasAttribute("preview-mode")}get maxSplats(){return this.getAttribute("max-splats")}get cameraPosition(){return this.getAttribute("camera-position")}get cameraTarget(){return this.getAttribute("camera-target")}get orbitSensitivity(){return this.getAttribute("orbit-sensitivity")}get panSensitivity(){return this.getAttribute("pan-sensitivity")}get zoomSensitivity(){return this.getAttribute("zoom-sensitivity")}get minDistance(){return this.getAttribute("min-distance")}get maxDistance(){return this.getAttribute("max-distance")}get enableNavigationCube(){return this.hasAttribute("enable-navigation-cube")}get navigationCubeSize(){return this.getAttribute("navigation-cube-size")}get navigationCubeTransition(){return this.getAttribute("navigation-cube-transition")}get navigationCubeParentId(){return this.getAttribute("navigation-cube-parent-id")}set src(t){null===t?this.removeAttribute("src"):this.setAttribute("src",t)}set width(t){null===t?this.removeAttribute("width"):this.setAttribute("width",t)}set height(t){null===t?this.removeAttribute("height"):this.setAttribute("height",t)}set enableStats(t){t?this.setAttribute("enable-stats",""):this.removeAttribute("enable-stats")}set autoFocus(t){t?this.setAttribute("auto-focus",""):this.removeAttribute("auto-focus")}set previewMode(t){t?this.setAttribute("preview-mode",""):this.removeAttribute("preview-mode")}set maxSplats(t){null===t?this.removeAttribute("max-splats"):this.setAttribute("max-splats",t)}set cameraPosition(t){null===t?this.removeAttribute("camera-position"):this.setAttribute("camera-position",t)}set cameraTarget(t){null===t?this.removeAttribute("camera-target"):this.setAttribute("camera-target",t)}set orbitSensitivity(t){null===t?this.removeAttribute("orbit-sensitivity"):this.setAttribute("orbit-sensitivity",t)}set panSensitivity(t){null===t?this.removeAttribute("pan-sensitivity"):this.setAttribute("pan-sensitivity",t)}set zoomSensitivity(t){null===t?this.removeAttribute("zoom-sensitivity"):this.setAttribute("zoom-sensitivity",t)}set minDistance(t){null===t?this.removeAttribute("min-distance"):this.setAttribute("min-distance",t)}set maxDistance(t){null===t?this.removeAttribute("max-distance"):this.setAttribute("max-distance",t)}set enableNavigationCube(t){t?this.setAttribute("enable-navigation-cube",""):this.removeAttribute("enable-navigation-cube")}set navigationCubeSize(t){null===t?this.removeAttribute("navigation-cube-size"):this.setAttribute("navigation-cube-size",t)}set navigationCubeTransition(t){null===t?this.removeAttribute("navigation-cube-transition"):this.setAttribute("navigation-cube-transition",t)}set navigationCubeParentId(t){null===t?this.removeAttribute("navigation-cube-parent-id"):this.setAttribute("navigation-cube-parent-id",t)}connectedCallback(){this._isDestroyed||this._initialize()}disconnectedCallback(){this._destroy()}attributeChangedCallback(t,e,i){if(e!==i&&(null===i||this._validateAttribute(t,i)))switch(this._updateConfigFromAttributes(),t){case"src":this._handleSrcChange(i);break;case"width":case"height":this._handleSizeChange();break;case"enable-stats":this._handleStatsChange()}}_validateAttribute(t,e){switch(t){case"width":case"height":return/^(\d+(\.\d+)?(px|%|em|rem|vh|vw|vmin|vmax)?|\d+)$/.test(e);case"max-splats":const t=parseInt(e,10);return!isNaN(t)&&t>0;case"orbit-sensitivity":case"pan-sensitivity":case"zoom-sensitivity":const i=parseFloat(e);return!isNaN(i)&&i>0;case"min-distance":case"max-distance":const s=parseFloat(e);return!isNaN(s)&&s>0;case"camera-position":case"camera-target":try{const t=JSON.parse(e);return Array.isArray(t)&&3===t.length&&t.every(t=>"number"==typeof t&&!isNaN(t))}catch{return!1}case"src":return e.length>0;case"enable-stats":case"auto-focus":case"preview-mode":case"enable-navigation-cube":return!0;case"navigation-cube-size":const n=parseFloat(e);return!isNaN(n)&&n>0;case"navigation-cube-transition":const r=parseFloat(e);return!isNaN(r)&&r>0;case"navigation-cube-parent-id":return e.length>0;default:return!0}}async _initialize(){if(!this._isInitialized)try{this.style.display="block",this.style.position="relative",this.style.overflow="hidden",this.hasAttribute("width")||this.style.width||(this.style.width="100%"),this.hasAttribute("height")||this.style.height||(this.style.height="100%"),this._canvas=document.createElement("canvas"),this._canvas.style.display="block",this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.outline="none",this._canvas.style.userSelect="none",this._canvas.style.touchAction="none",this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("role","img"),this._canvas.setAttribute("aria-label","3D Splat Viewer"),this.appendChild(this._canvas);try{window.ResizeObserver&&(this._hostResizeObserver=new ResizeObserver(()=>{try{this._core?.updateCanvasResolution()}catch{}}),this._hostResizeObserver.observe(this),this.parentElement&&this._hostResizeObserver.observe(this.parentElement))}catch{}this._updateConfigFromAttributes(),this._core=new SplatViewerCore(this._config),this._core.init(this._canvas),this._setupEventListeners(),this._handleSizeChange(),await this._core.whenReady();const t=this.src;t&&await this.load(t),this._isInitialized=!0,this.dispatchEvent(sV("ready",void 0))}catch(t){this._cleanupOnError(),this.dispatchEvent(sV("error",{message:`Failed to initialize: ${t instanceof Error?t.message:"Unknown error"}`,code:"INIT_FAILED"}))}}_cleanupOnError(){try{this._core&&(this._core.destroy(),this._core=null),this._canvas&&this._canvas.parentNode&&(this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this._isInitialized=!1}catch(t){}}_destroy(){if(!this._isDestroyed)try{this._hostResizeObserver&&(this._hostResizeObserver.disconnect(),this._hostResizeObserver=null),this._core&&(this._core.destroy(),this._core=null),this._canvas&&this._canvas.parentNode&&(this._canvas.parentNode.removeChild(this._canvas),this._canvas=null),this._isDestroyed=!0,this._isInitialized=!1}catch(t){}}_updateConfigFromAttributes(){const t=function(t){const e={},i=t.getAttribute("auto-focus");null!==i&&(e.autoFocus=Cz(i));const s=t.getAttribute("enable-stats");null!==s&&(e.enableStats=Cz(s));const n=t.getAttribute("preview-mode");null!==n&&(e.previewMode=Cz(n));const r=t.getAttribute("max-splats");null!==r&&(e.maxSplats=Mz(r,wz.maxSplats));const a=t.getAttribute("camera-position"),o=t.getAttribute("camera-target");if(a||o){const t=Az(a),i=Az(o);e.camera={...wz.camera,...t&&{position:t},...i&&{target:i}}}const l=t.getAttribute("enable-navigation-cube");null!==l&&(e.navigationCube={...wz.navigationCube,enabled:Cz(l)});const h=t.getAttribute("navigation-cube-size");null!==h&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,cubeSize:Mz(h,wz.navigationCube.cubeSize)});const c=t.getAttribute("navigation-cube-transition");null!==c&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,transitionDuration:Mz(c,wz.navigationCube.transitionDuration)});const d=t.getAttribute("navigation-cube-parent-id");null!==d&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,enabled:!0,parentElementId:d});const u=t.getAttribute("navigation-cube-rotation-speed");return null!==u&&(e.navigationCube={...wz.navigationCube,...e.navigationCube,continuousRotationSpeed:Mz(u,wz.navigationCube.continuousRotationSpeed)}),e}(this);var e,i;this._config=(e=wz,i=t,{...e,...i,camera:{...e.camera,...i.camera},navigationCube:{...e.navigationCube,...i.navigationCube}})}_validateSource(t){if(!t||"string"!=typeof t)return!1;if(0===t.trim().length)return!1;try{return new URL(t),!0}catch{return!!t.startsWith("data:")||!(!t.startsWith("./")&&!t.startsWith("../")&&t.includes("://"))}}async _handleSrcChange(t){if(this._core&&t)if(this._validateSource(t))try{await this.load(t)}catch(t){await this._handleError(t,"LOAD_FAILED")}else this.dispatchEvent(sV("error",{message:`Invalid source: ${t}`,code:"INVALID_SOURCE"}))}_handleSizeChange(){if(!this._canvas)return;const t=this.width,e=this.height;if(t){const e=/(px|%|em|rem|vh|vw|vmin|vmax)$/.test(t);this.style.width=e?t:`${t}px`}else this.style.width="100%";if(e){const t=/(px|%|em|rem|vh|vw|vmin|vmax)$/.test(e);this.style.height=t?e:`${e}px`}else this.style.height="100%";this._canvas.style.width="100%",this._canvas.style.height="100%"}_handleStatsChange(){this._core}_setupEventListeners(){this._core&&(this._core.on("loading-start",t=>{this.dispatchEvent(sV("loading-start",t.detail))}),this._core.on("loading-progress",t=>{this.dispatchEvent(sV("loading-progress",t.detail))}),this._core.on("loaded",t=>{this.dispatchEvent(sV("loaded",t.detail))}),this._core.on("error",t=>{this.dispatchEvent(sV("error",t.detail))}),this._core.on("camera-change",t=>{this.dispatchEvent(sV("camera-change",t.detail))}),this._core.on("interaction-start",t=>{this.dispatchEvent(sV("interaction-start",t.detail))}),this._core.on("interaction-end",t=>{this.dispatchEvent(sV("interaction-end",t.detail))}),this._core.on("camera-mode-changed",t=>{this.dispatchEvent(sV("camera-mode-changed",t.detail))}),this._core.on("fly-camera-move",t=>{this.dispatchEvent(sV("fly-camera-move",t.detail))}),this._core.on("fly-camera-look",t=>{this.dispatchEvent(sV("fly-camera-look",t.detail))}),this._core.on("camera-fov-changed",t=>{this.dispatchEvent(sV("camera-fov-changed",t.detail))}),this._core.on("background-color-changed",t=>{this.dispatchEvent(sV("background-color-changed",t.detail))}),this._core.on("splat-center-size-changed",t=>{this.dispatchEvent(sV("splat-center-size-changed",t.detail))}),this._core.on("spherical-harmonics-bands-changed",t=>{this.dispatchEvent(sV("spherical-harmonics-bands-changed",t.detail))}),this._core.on("model-added",t=>{this.dispatchEvent(sV("model-added",t.detail))}),this._core.on("model-removed",t=>{this.dispatchEvent(sV("model-removed",t.detail))}),this._core.on("scene-cleared",t=>{this.dispatchEvent(sV("scene-cleared",t.detail))}))}async load(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");if("string"==typeof t){if(!this._validateSource(t))throw new Error(`Invalid source string: ${t}`)}else if(t instanceof File){if(0===t.size)throw new Error("File is empty")}else{if(!(t instanceof Blob))throw new Error("Invalid source type. Expected string, File, or Blob.");if(0===t.size)throw new Error("Blob is empty")}try{return await this._core.load(t,e)}catch(t){if(await this._handleError(t,"LOAD_FAILED"),t instanceof Error)throw new Error(`Failed to load model: ${t.message}`);throw new Error("Failed to load model: Unknown error")}}async loadFile(t,e){return this.load(t,e)}async loadBlob(t,e){return this.load(t,e)}focus(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.focus(t)}setCameraPosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraPosition(t)}setCameraTarget(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraTarget(t)}resetCamera(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.resetCamera()}clear(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clear()}getDebugInfo(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.debugInfo()}get isReady(){return this._isInitialized&&!this._isDestroyed&&null!==this._core}get config(){return{...this._config}}async _handleError(t,e){const i="string"==typeof t?t:t?.message||"Unknown error";this.dispatchEvent(sV("error",{message:e?`${e}: ${i}`:i,code:e||"ERROR"}))}async addModel(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return await this._core.addModel(t,e)}removeModel(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.removeModel(t)}getModels(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModels()}getModelStats(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModelStats(t)}getAllModelStats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllModelStats()}getSceneStats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSceneStats()}setModelVisible(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelVisible(t,e)}setModelsVisibleByName(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelsVisibleByName(t,e)}setCameraMode(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraMode(t)}getCameraMode(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getCameraMode()}setFlyCameraConfig(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setFlyCameraConfig(t)}getFlyCameraConfig(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraConfig()}getFlyCameraState(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraState()}setCameraFOV(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setCameraFOV(t)}getCameraFOV(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getCameraFOV()}async animateCameraFOV(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.animateCameraFOV(t,e)}setFlyCameraSpeed(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setFlyCameraSpeed(t)}getFlyCameraSpeed(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getFlyCameraSpeed()}setBackgroundColor(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBackgroundColor(t)}getBackgroundColor(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBackgroundColor()}async animateBackgroundColor(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.animateBackgroundColor(t,e)}async setSkyboxEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");await this._core.setSkyboxEnabled(t)}isSkyboxEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isSkyboxEnabled()}setSplatCenterSize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSplatCenterSize(t)}getSplatCenterSize(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSplatCenterSize()}setSphericalHarmonicsBands(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSphericalHarmonicsBands(t)}getSphericalHarmonicsBands(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSphericalHarmonicsBands()}setGridEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setGridEnabled(t)}isGridEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isGridEnabled()}setBoundingBoxEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoundingBoxEnabled(t)}isBoundingBoxEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isBoundingBoxEnabled()}setBoundingBoxSelection(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoundingBoxSelection(t)}getBoundingBoxSelection(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoundingBoxSelection()}createSelectionBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.createSelectionBox(t)}removeSelectionBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.removeSelectionBox(t)}clearSelectionBoxes(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSelectionBoxes()}setBoxSize(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxSize(t,e,i,s)}getBoxSize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoxSize(t)}setBoxPosition(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxPosition(t,e,i,s)}getBoxPosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getBoxPosition(t)}setBoxColor(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setBoxColor(t,e,i,s)}showBox(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.showBox(t,e)}getAllSelectionBoxes(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllSelectionBoxes()}getSelectedBoxId(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedBoxId()}selectBox(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectBox(t)}setBoxSelectionEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setBoxSelectionEnabled(t)}isBoxSelectionEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isBoxSelectionEnabled()}createSelectionSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.createSelectionSphere(t)}removeSelectionSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.removeSelectionSphere(t)}clearSelectionSpheres(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSelectionSpheres()}setSphereRadius(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSphereRadius(t,e)}getSphereRadius(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSphereRadius(t)}setSpherePosition(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSpherePosition(t,e,i,s)}getSpherePosition(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSpherePosition(t)}setSphereColor(t,e,i,s){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.setSphereColor(t,e,i,s)}showSphere(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.showSphere(t,e)}getAllSelectionSpheres(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getAllSelectionSpheres()}getSelectedSphereId(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedSphereId()}selectSphere(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSphere(t)}setSphereSelectionEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setSphereSelectionEnabled(t)}isSphereSelectionEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isSphereSelectionEnabled()}selectSplatsInSphereById(t,e,i=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInSphereById(t,e,i)}getSplatDataDebugInfo(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSplatDataDebugInfo(t)}selectSplatsInBox(t,e,i=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInBox(t,e,i)}selectSplatsInSphere(t,e,i,s=!1){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.selectSplatsInSphere(new K(t.x,t.y,t.z),e,i,s)}clearSplatSelection(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.clearSplatSelection()}getSelectedSplats(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getSelectedSplats()}setHighlightEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightEnabled(t)}isHighlightEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isHighlightEnabled()}setHighlightColor(t,e,i,s=.7){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightColor(t,e,i,s)}getHighlightColor(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getHighlightColor()}setHighlightMode(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightMode(t)}getHighlightMode(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getHighlightMode()}setHighlightOverlayStyle(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightOverlayStyle(t)}setHighlightOverlaySize(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setHighlightOverlaySize(t)}setOutlineEnabled(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setOutlineEnabled(t)}isOutlineEnabled(){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.isOutlineEnabled()}applyTransformMatrix(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.applyTransformMatrix(t,e)}setModelPosition(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelPosition(t,e)}setModelRotation(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelRotation(t,e)}setModelScale(t,e){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.setModelScale(t,e)}getModelTransform(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");return this._core.getModelTransform(t)}resetModelTransform(t){if(!this._core)throw new Error("SplatViewerElement: Core not initialized. Call connectedCallback first.");this._core.resetModelTransform(t)}}customElements.get("splat-viewer")||customElements.define("splat-viewer",SplatViewerElement),t.SplatViewerElement=SplatViewerElement,t.default=SplatViewerElement,Object.defineProperty(t,"__esModule",{value:!0})});
|